Fix coverart download.
[clinton/xbmc-groove.git] / resources / lib / GroovesharkAPI.py
1 import socket, hmac, urllib, urllib2, pprint, md5, re, sha, time, random, os, pickle, uuid, tempfile
2
3 SESSION_EXPIRY = 518400 # 6 days in seconds
4
5 # GrooveAPI constants
6 THUMB_URL = 'http://beta.grooveshark.com/static/amazonart/m'
7 SONG_LIMIT = 25
8 ALBUM_LIMIT = 15
9 ARTIST_LIMIT = 15
10 SONG_SUFFIX = '.mp3'
11
12 # GrooveSong constants
13 DOMAIN = "grooveshark.com"
14 HOME_URL = "http://listen." + DOMAIN
15 API_URL = "http://cowbell." + DOMAIN + "/more.php"
16 SERVICE_URL = "http://cowbell." + DOMAIN + "/service.php"
17 TOKEN_URL = "http://cowbell." + DOMAIN + "/more.php"
18
19 CLIENT_NAME = "gslite"
20 CLIENT_VERSION = "20101012.37"
21 HEADERS = {"Content-Type": "application/json",
22 "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)",
23 "Referer": "http://listen.grooveshark.com/main.swf?cowbell=fe87233106a6cef919a1294fb2c3c05f"}
24
25 RE_SESSION = re.compile('"sessionID":"\s*?([A-z0-9]+)"')
26 RANDOM_CHARS = "1234567890abcdef"
27
28 # Get a song
29 class GrooveSong:
30
31 def __init__(self):
32
33 import simplejson
34 self.simplejson = simplejson
35
36 self.cacheDir = os.path.join(tempfile.gettempdir(), 'groovesong')
37 self._lastSessionTime = 0
38 self.uuid = self._getUUID()
39
40 self._getSavedSession()
41 # session ids last 1 week
42 if self.sessionID == '' or time.time() - self._lastSessionTime >= SESSION_EXPIRY:
43 self.sessionID = self._getSession(HOME_URL)
44 if self.sessionID == '':
45 raise StandardError('Failed to get session id')
46 else:
47 print "New GrooveSong session id: " + self.sessionID
48 self._setSavedSession()
49
50 # The actual call to the API
51 def _callRemote(self, method, params, type="default"):
52 postData = {
53 "header": {
54 "client": CLIENT_NAME,
55 "clientRevision": CLIENT_VERSION,
56 "uuid": self.uuid,
57 "session": self.sessionID},
58 "country": {"IPR":"1021", "ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"},
59 "privacy": 1,
60 "parameters": params,
61 "method": method}
62
63 token = self._getMethodToken(method)
64 if token == None:
65 raise StandardError("Cannot get token")
66
67 postData["header"]["token"] = token
68 if type == "service":
69 url = SERVICE_URL + "?" + method
70 else:
71 url = API_URL + "?" + method
72
73 postData = self.simplejson.dumps(postData)
74 print "GrooveSong URL: " + url
75 request = urllib2.Request(url, postData, HEADERS)
76
77 response = urllib2.urlopen(request).read()
78 try:
79 response = self.simplejson.loads(response)
80 print "GrooveSong Response..."
81 pprint.pprint(response)
82 except:
83 raise StandardError("API error: " + response)
84 try:
85 response["fault"]
86 except KeyError:
87 return response
88 else:
89 raise StandardError("API error: " + response["fault"]["message"])
90
91 # Generate a random uuid
92 def _getUUID(self):
93 return str(uuid.uuid4())
94
95 # Make a token ready for a request header
96 def _getMethodToken(self, method):
97 self._token = self._getCommunicationToken()
98 if self._token == None:
99 return None
100
101 randomChars = ""
102 while 6 > len(randomChars):
103 randomChars = randomChars + random.choice(RANDOM_CHARS)
104
105 token = sha.new(method + ":" + self._token + ":quitStealinMahShit:" + randomChars).hexdigest()
106
107 return randomChars + token
108
109 # Generate a communication token
110 def _getCommunicationToken(self):
111 params = {"secretKey": self._getSecretKey(self.sessionID)}
112 postData = {
113 "header": {
114 "client": CLIENT_NAME,
115 "clientRevision": CLIENT_VERSION,
116 "uuid": self.uuid,
117 "session": self.sessionID},
118 "country": {"IPR":"1021", "ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"},
119 "privacy": 1,
120 "parameters": params,
121 "method": "getCommunicationToken"}
122
123 postData = self.simplejson.dumps(postData)
124 request = urllib2.Request(TOKEN_URL, postData, HEADERS)
125 response = urllib2.urlopen(request).read()
126 try:
127 response = self.simplejson.loads(response)
128 except:
129 raise StandardError("API error: " + response)
130 try:
131 response["fault"]
132 except KeyError:
133 return response["result"]
134 else:
135 return None
136
137 # Generate a secret key from a sessionID
138 def _getSecretKey(self, sessionID):
139 return md5.new(sessionID).hexdigest()
140
141 # Get a session id from some HTML
142 def _getSession(self, html):
143 html = urllib2.urlopen(HOME_URL).read()
144 session = RE_SESSION.search(html)
145 if session:
146 self._lastSessionTime = time.time()
147 return session.group(1)
148 else:
149 return None
150
151 def _getSavedSession(self):
152 path = os.path.join(self.cacheDir, 'session.dmp')
153 try:
154 f = open(path, 'rb')
155 session = pickle.load(f)
156 self.sessionID = session['sessionID']
157 self._lastSessionTime = session['lastSessionTime']
158 f.close()
159 except:
160 self.sessionID = ''
161 self._lastSessionTime = 0
162 pass
163
164 def _setSavedSession(self):
165 try:
166 # Create the 'data' directory if it doesn't exist.
167 if not os.path.exists(self.cacheDir):
168 os.makedirs(self.cacheDir)
169 path = os.path.join(self.cacheDir, 'session.dmp')
170 f = open(path, 'wb')
171 session = {'sessionID' : self.sessionID, 'lastSessionTime' : self._lastSessionTime}
172 pickle.dump(session, f, protocol=pickle.HIGHEST_PROTOCOL)
173 f.close()
174 except:
175 print "An error occurred during save session"
176 pass
177
178 # Gets a stream key and host to get song content
179 def _getStreamDetails(self, songID):
180 params = {
181 "songID": songID,
182 "prefetch": False,
183 "mobile": False,
184 "country": {"IPR":"1021","ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"}
185 }
186 response = self._callRemote("getStreamKeyFromSongIDEx", params)
187 try:
188 self._lastStreamKey = response["result"]["streamKey"]
189 self._lastStreamServer = response["result"]["ip"]
190 self._lastStreamServerID = response["result"]["streamServerID"]
191 return True
192 except:
193 return False
194
195 # Tells Grooveshark you have downloaded a song
196 def _markSongDownloaded(self, songID):
197 params = {
198 "streamKey": self._lastStreamKey,
199 "streamServerID": self._lastStreamServerID,
200 "songID": songID}
201 self._callRemote("markSongDownloaded", params)
202
203 # Get the song URL
204 def getSongURL(self, songID):
205 if self._getStreamDetails(songID) == True:
206 postData = {"streamKey": self._lastStreamKey}
207 postData = urllib.urlencode(postData)
208 return "http://" + self._lastStreamServer + "/stream.php?" + str(postData)
209 else:
210 return ''
211
212 # Main API
213 class GrooveAPI:
214
215 sessionID = ''
216 userID = 0
217 host = 'api.grooveshark.com'
218 lastSessionTime = 0
219
220 # Constructor
221 def __init__(self):
222
223 import simplejson
224 self.simplejson = simplejson
225 socket.setdefaulttimeout(40)
226
227 self.cacheDir = os.path.join(tempfile.gettempdir(), 'grooveapi')
228 if os.path.isdir(self.cacheDir) == False:
229 os.makedirs(self.cacheDir)
230 print "Made " + self.cacheDir
231
232 self._getSavedSession()
233 # session ids last 1 week
234 if self.sessionID == '' or time.time()- self.lastSessionTime >= SESSION_EXPIRY:
235 self.sessionID = self._getSessionID()
236 if self.sessionID == '':
237 raise StandardError('Failed to get session id')
238 else:
239 print "New GrooveAPI session id: " + self.sessionID
240 self._setSavedSession()
241
242 # Sort keys
243 def _keySort(self, d):
244 return [(k,d[k]) for k in sorted(d.keys())]
245
246 # Make a message sig
247 def _createMessageSig(self, method, params, secret):
248 args = self._keySort(params);
249 data = '';
250 for arg in args:
251 data += str(arg[0])
252 data += str(arg[1])
253 data = method + data
254
255 h = hmac.new(secret, data)
256 return h.hexdigest()
257
258 # The actual call to the API
259 def _callRemote(self, method, params = {}):
260 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'))
261 print url
262 req = urllib2.Request(url)
263 response = urllib2.urlopen(req)
264 result = response.read()
265 print "Response..."
266 pprint.pprint(result)
267 response.close()
268 try:
269 result = self.simplejson.loads(result)
270 return result
271 except:
272 return []
273
274 # Get a session id
275 def _getSessionID(self):
276 params = {}
277 result = self._callRemote('startSession', params)
278 self.lastSessionTime = time.time()
279 return result['result']['sessionID']
280
281 def _getSavedSession(self):
282 path = os.path.join(self.cacheDir, 'session.dmp')
283 try:
284 f = open(path, 'rb')
285 session = pickle.load(f)
286 self.sessionID = session['sessionID']
287 self.lastSessionTime = session['lastSessionTime']
288 self.userID = session['userID']
289 f.close()
290 except:
291 self.sessionID = ''
292 self.lastSessionTime = 0
293 self.userID = 0
294 pass
295
296 def _setSavedSession(self):
297 try:
298 # Create the directory if it doesn't exist.
299 if not os.path.exists(self.cacheDir):
300 os.makedirs(self.cacheDir)
301 path = os.path.join(self.cacheDir, 'session.dmp')
302 f = open(path, 'wb')
303 session = { 'sessionID' : self.sessionID, 'lastSessionTime' : self.lastSessionTime, 'userID': self.userID}
304 pickle.dump(session, f, protocol=pickle.HIGHEST_PROTOCOL)
305 f.close()
306 except:
307 print "An error occurred during save session"
308 pass
309
310 # Make user authentication token
311 def _getUserToken(self, username, password):
312 return md5.new(username.lower() + md5.new(password).hexdigest()).hexdigest()
313
314 # Authenticates the user for current API session
315 def _authenticateUser(self, username, token):
316 params = {'sessionID': self.sessionID, 'username': username, 'token': token}
317 result = self._callRemote('authenticateUser', params)
318 return result['result']['UserID']
319
320 # Login
321 def login(self, username, password):
322 if self.userID <= 0:
323 # Check cache
324 self._getSavedSession()
325 if self.userID <= 0:
326 token = self._getUserToken(username, password)
327 self.userID = self._authenticateUser(username, token)
328 if self.userID > 0:
329 self._setSavedSession()
330 return self.userID
331
332 # Logs the user out
333 def logout(self):
334 result = self._callRemote('logout', {'sessionID' : self.sessionID})
335 if 'result' in result and result['result']['success'] == True:
336 self.userID = 0
337 self._setSavedSession()
338 return True
339 return False
340
341 # Search for albums
342 def getArtistSearchResults(self, query, limit=ARTIST_LIMIT):
343 result = self._callRemote('getArtistSearchResults', {'query' : query,'limit' : limit})
344 if 'result' in result:
345 return self._parseArtists(result)
346 else:
347 return []
348
349 # Search for albums
350 def getAlbumSearchResults(self, query, limit=ALBUM_LIMIT):
351 result = self._callRemote('getAlbumSearchResults', {'query' : query,'limit' : limit})
352 if 'result' in result:
353 return self._parseAlbums(result)
354 else:
355 return []
356
357 # Search for songs
358 def getSongSearchResults(self, query, limit=SONG_LIMIT):
359 result = self._callRemote('getSongSearchResultsEx', {'query' : query, 'limit' : limit})
360 if 'result' in result:
361 return self._parseSongs(result)
362 else:
363 return []
364
365 # Get artists albums
366 def getArtistAlbums(self, artistID, limit=ALBUM_LIMIT):
367 result = self._callRemote('getArtistAlbums', {'artistID' : artistID})
368 if 'result' in result:
369 return self._parseAlbums(result, limit)
370 else:
371 return []
372
373 # Get album songs
374 def getAlbumSongs(self, albumID, limit=SONG_LIMIT):
375 result = self._callRemote('getAlbumSongsEx', {'albumID' : albumID, 'limit' : limit})
376 if 'result' in result:
377 return self._parseSongs(result)
378 else:
379 return []
380
381 # Get artist's popular songs
382 def getArtistPopularSongs(self, artistID, limit = SONG_LIMIT):
383 result = self._callRemote('getArtistPopularSongs', {'artistID' : artistID})
384 if 'result' in result:
385 return self._parseSongs(result, limit)
386 else:
387 return []
388
389 # Gets the popular songs
390 def getPopularSongsToday(self, limit=SONG_LIMIT):
391 result = self._callRemote('getPopularSongsToday', {'limit' : limit})
392 if 'result' in result:
393 # Note limit is broken in the Grooveshark getPopularSongsToday method
394 return self._parseSongs(result, limit)
395 else:
396 return []
397
398 # Gets the favorite songs of the logged-in user
399 def getUserFavoriteSongs(self):
400 if (self.userID == 0):
401 return [];
402 result = self._callRemote('getUserFavoriteSongs', {'sessionID' : self.sessionID})
403 if 'result' in result:
404 return self._parseSongs(result)
405 else:
406 return []
407
408 # Add song to user favorites
409 def addUserFavoriteSong(self, songID):
410 if (self.userID == 0):
411 return False;
412 result = self._callRemote('addUserFavoriteSong', {'sessionID' : self.sessionID, 'songID' : songID})
413 return result['result']['success']
414
415 # Get the url to link to a song on Grooveshark
416 def getSongURLFromSongID(self, songID):
417 song = GrooveSong()
418 url = song.getSongURL(songID)
419 print "Got song URL " + url
420 return url
421
422 # Get the url to link to a song on Grooveshark
423 def getSongInfo(self, songID):
424 result = self._callRemote('getSongInfoEx', {'songID' : songID})
425 if 'result' in result and 'SongID' in result['result']:
426 info = result['result']
427 if 'CoverArtFilename' in info and info['CoverArtFilename'] != None:
428 info['CoverArtFilename'] = THUMB_URL+info['CoverArtFilename'].encode('ascii', 'ignore')
429 else:
430 info['CoverArtFilename'] = 'None'
431 return info
432 else:
433 return 'None'
434
435 # Gets the playlists of the logged-in user
436 def getUserPlaylists(self):
437 if (self.userID == 0):
438 return [];
439 result = self._callRemote('getUserPlaylists', {'sessionID' : self.sessionID})
440 if 'result' in result:
441 return self._parsePlaylists(result)
442 else:
443 return []
444
445 # Get userid from name
446 def _getUserIDFromUsername(self, username):
447 result = self._callRemote('getUserIDFromUsername', {'username' : username})
448 if 'result' in result and result['result']['UserID'] > 0:
449 return result['result']['UserID']
450 else:
451 return 0
452
453 # Gets the playlists of the logged-in user
454 def getUserPlaylistsEx(self, username):
455 userID = self._getUserIDFromUsername(username)
456 if (userID > 0):
457 result = self._callRemote('getUserPlaylistsEx', {'userID' : userID})
458 if 'result' in result and result['result']['playlists'] != None:
459 playlists = result['result']['playlists']
460 return self._parsePlaylists(playlists)
461 else:
462 return []
463
464 # Creates a playlist with songs
465 def createPlaylist(self, name, songIDs):
466 result = self._callRemote('createPlaylist', {'name' : name, 'songIDs' : songIDs, 'sessionID' : self.sessionID})
467 if 'result' in result and result['result']['success'] == True:
468 return result['result']['playlistID']
469 elif 'errors' in result:
470 return 0
471
472 # Sets the songs for a playlist
473 def setPlaylistSongs(self, playlistID, songIDs):
474 result = self._callRemote('setPlaylistSongs', {'playlistID' : playlistID, 'songIDs' : songIDs, 'sessionID' : self.sessionID})
475 if 'result' in result and result['result']['success'] == True:
476 return True
477 else:
478 return False
479
480 # Gets the songs of a playlist
481 def getPlaylistSongs(self, playlistID):
482 result = self._callRemote('getPlaylistSongs', {'playlistID' : playlistID});
483 if 'result' in result:
484 return self._parseSongs(result)
485 else:
486 return []
487
488 # Check the service
489 def pingService(self,):
490 result = self._callRemote('pingService', {});
491 if 'result' in result and result['result'] != '':
492 return True
493 else:
494 return False
495
496 # Extract song data
497 def _parseSongs(self, items, limit=0):
498 if 'result' in items:
499 i = 0
500 list = []
501 index = ''
502 l = -1
503 try:
504 if 'songs' in items['result'][0]:
505 l = len(items['result'][0]['songs'])
506 index = 'songs[]'
507 except: pass
508 try:
509 if l < 0 and 'songs' in items['result']:
510 l = len(items['result']['songs'])
511 index = 'songs'
512 except: pass
513 try:
514 if l < 0 and 'song' in items['result']:
515 l = 1
516 index = 'song'
517 except: pass
518 try:
519 if l < 0:
520 l = len(items['result'])
521 except: pass
522
523 if limit > 0 and l > limit:
524 l = limit
525 while(i < l):
526 if index == 'songs[]':
527 s = items['result'][0]['songs'][i]
528 elif index == 'songs':
529 s = items['result'][index][i]
530 elif index == 'song':
531 s = items['result'][index]
532 else:
533 s = items['result'][i]
534 if 'CoverArtFilename' not in s:
535 info = self.getSongInfo(s['SongID'])
536 coverart = info['CoverArtFilename']
537 elif s['CoverArtFilename'] != None:
538 coverart = THUMB_URL+s['CoverArtFilename'].encode('ascii', 'ignore')
539 else:
540 coverart = 'None'
541 list.append([s['SongName'].encode('ascii', 'ignore'),\
542 s['SongID'],\
543 s['AlbumName'].encode('ascii', 'ignore'),\
544 s['AlbumID'],\
545 s['ArtistName'].encode('ascii', 'ignore'),\
546 s['ArtistID'],\
547 coverart])
548 i = i + 1
549 return list
550 else:
551 return []
552
553 # Extract artist data
554 def _parseArtists(self, items):
555 if 'result' in items:
556 i = 0
557 list = []
558 artists = items['result']['artists']
559 while(i < len(artists)):
560 s = artists[i]
561 list.append([s['ArtistName'].encode('ascii', 'ignore'),\
562 s['ArtistID']])
563 i = i + 1
564 return list
565 else:
566 return []
567
568 # Extract album data
569 def _parseAlbums(self, items, limit=0):
570 if 'result' in items:
571 i = 0
572 list = []
573 try:
574 albums = items['result']['albums']
575 except:
576 res = items['result'][0]
577 albums = res['albums']
578 l = len(albums)
579 if limit > 0 and l > limit:
580 l = limit
581 while(i < l):
582 s = albums[i]
583 if 'CoverArtFilename' in s and s['CoverArtFilename'] != None:
584 coverart = THUMB_URL+s['CoverArtFilename'].encode('ascii', 'ignore')
585 else:
586 coverart = 'None'
587 list.append([s['ArtistName'].encode('ascii', 'ignore'),\
588 s['ArtistID'],\
589 s['AlbumName'].encode('ascii', 'ignore'),\
590 s['AlbumID'],\
591 coverart])
592 i = i + 1
593 return list
594 else:
595 return []
596
597 def _parsePlaylists(self, items):
598 i = 0
599 list = []
600 if 'result' in items:
601 playlists = items['result']
602 elif len(items) > 0:
603 playlists = items
604 else:
605 return []
606
607 while (i < len(playlists)):
608 s = playlists[i]
609 list.append([s['Name'].encode('ascii', 'ignore'), s['PlaylistID']])
610 i = i + 1
611 return list
612
613 # Test
614 #import sys
615 #res = []
616 #groovesharkApi = GrooveAPI()
617 #res = groovesharkApi.pingService()
618 #res = groovesharkApi.login(sys.argv[1], sys.argv[2])
619 #songIDs = ['23404546','23401810','23401157']
620 #res = groovesharkApi.createPlaylist("Test")
621 #res = groovesharkApi.setPlaylistSongs(res, songIDs)
622 #res = groovesharkApi.getPlaylistSongs(42251632)
623 #res = groovesharkApi.getSongSearchResults('jimmy jazz', 3)
624 #res = groovesharkApi.getPopularSongsToday(3)
625 #res = groovesharkApi.getSongURLFromSongID('26579347')
626 #res = groovesharkApi.getAlbumSearchResults('london calling', 3)
627 #res = groovesharkApi.getArtistAlbums('52283')
628 #res = groovesharkApi.getArtistSearchResults('the clash', 3)
629 #res = groovesharkApi.getUserFavoriteSongs()
630 #res = groovesharkApi.getUserPlaylists()
631 #res = groovesharkApi.getSongInfo('27425375')
632 #res = groovesharkApi.getPlaylistSongs(40902662)
633 #res = groovesharkApi.addUserFavoriteSong('27425375')
634 #res = groovesharkApi.logout()
635 #res = groovesharkApi.getUserPlaylistsEx('stephendenham')
636 #res = groovesharkApi.getArtistPopularSongs('3707')
637 #
638 #pprint.pprint(res)