Use song URL for playback.
[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/'
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 # Gets the popular songs
382 def getPopularSongsToday(self, limit=SONG_LIMIT):
383 result = self._callRemote('getPopularSongsToday', {'limit' : limit})
384 if 'result' in result:
385 # Note limit is broken in the Grooveshark getPopularSongsToday method
386 return self._parseSongs(result, limit)
387 else:
388 return []
389
390 # Gets the favorite songs of the logged-in user
391 def getUserFavoriteSongs(self):
392 if (self.userID == 0):
393 return [];
394 result = self._callRemote('getUserFavoriteSongs', {'sessionID' : self.sessionID})
395 if 'result' in result:
396 return self._parseSongs(result)
397 else:
398 return []
399
400 # Add song to user favorites
401 def addUserFavoriteSong(self, songID):
402 if (self.userID == 0):
403 return False;
404 result = self._callRemote('addUserFavoriteSong', {'sessionID' : self.sessionID, 'songID' : songID})
405 return result['result']['success']
406
407 # Get the url to link to a song on Grooveshark
408 def getSongURLFromSongID(self, songID):
409 song = GrooveSong()
410 url = song.getSongURL(songID)
411 print "Got song URL " + url
412 return url
413
414 # Get the url to link to a song on Grooveshark
415 def getSongInfo(self, songID):
416 result = self._callRemote('getSongInfoEx', {'songID' : songID})
417 if 'result' in result and 'SongID' in result['result']:
418 info = result['result']
419 if 'CoverArtFilename' in info and info['CoverArtFilename'] != None:
420 info['CoverArtFilename'] = THUMB_URL+info['CoverArtFilename'].encode('ascii', 'ignore')
421 else:
422 info['CoverArtFilename'] = 'None'
423 return info
424 else:
425 return 'None'
426
427 # Gets the playlists of the logged-in user
428 def getUserPlaylists(self):
429 if (self.userID == 0):
430 return [];
431 result = self._callRemote('getUserPlaylists', {'sessionID' : self.sessionID})
432 if 'result' in result:
433 return self._parsePlaylists(result)
434 else:
435 return []
436
437 # Creates a playlist with songs
438 def createPlaylist(self, name, songIDs):
439 result = self._callRemote('createPlaylist', {'name' : name, 'songIDs' : songIDs, 'sessionID' : self.sessionID})
440 if 'result' in result and result['result']['success'] == True:
441 return result['result']['playlistID']
442 elif 'errors' in result:
443 return 0
444
445 # Sets the songs for a playlist
446 def setPlaylistSongs(self, playlistID, songIDs):
447 result = self._callRemote('setPlaylistSongs', {'playlistID' : playlistID, 'songIDs' : songIDs, 'sessionID' : self.sessionID})
448 if 'result' in result and result['result']['success'] == True:
449 return True
450 else:
451 return False
452
453 # Gets the songs of a playlist
454 def getPlaylistSongs(self, playlistID):
455 result = self._callRemote('getPlaylistSongs', {'playlistID' : playlistID});
456 if 'result' in result:
457 return self._parseSongs(result)
458 else:
459 return []
460
461 # Check the service
462 def pingService(self,):
463 result = self._callRemote('pingService', {});
464 if 'result' in result and result['result'] != '':
465 return True
466 else:
467 return False
468
469 # Extract song data
470 def _parseSongs(self, items, limit=0):
471 if 'result' in items:
472 i = 0
473 list = []
474 if 'songs' in items['result']:
475 l = len(items['result']['songs'])
476 index = 'songs'
477 elif 'song' in items['result']:
478 l = 1
479 index = 'song'
480 else:
481 l = len(items['result'])
482 index = ''
483 if limit > 0 and l > limit:
484 l = limit
485 while(i < l):
486 if index == 'songs':
487 s = items['result'][index][i]
488 elif index == 'song':
489 s = items['result'][index]
490 else:
491 s = items['result'][i]
492 if 'CoverArtFilename' not in s:
493 info = self.getSongInfo(s['SongID'])
494 coverart = info['CoverArtFilename']
495 elif s['CoverArtFilename'] != None:
496 coverart = THUMB_URL+s['CoverArtFilename'].encode('ascii', 'ignore')
497 else:
498 coverart = 'None'
499 list.append([s['SongName'].encode('ascii', 'ignore'),\
500 s['SongID'],\
501 s['AlbumName'].encode('ascii', 'ignore'),\
502 s['AlbumID'],\
503 s['ArtistName'].encode('ascii', 'ignore'),\
504 s['ArtistID'],\
505 coverart])
506 i = i + 1
507 return list
508 else:
509 return []
510
511 # Extract artist data
512 def _parseArtists(self, items):
513 if 'result' in items:
514 i = 0
515 list = []
516 artists = items['result']['artists']
517 while(i < len(artists)):
518 s = artists[i]
519 list.append([s['ArtistName'].encode('ascii', 'ignore'),\
520 s['ArtistID']])
521 i = i + 1
522 return list
523 else:
524 return []
525
526 # Extract album data
527 def _parseAlbums(self, items, limit=0):
528 if 'result' in items:
529 i = 0
530 list = []
531 try:
532 albums = items['result']['albums']
533 except:
534 res = items['result'][0]
535 albums = res['albums']
536 l = len(albums)
537 if limit > 0 and l > limit:
538 l = limit
539 while(i < l):
540 s = albums[i]
541 if 'CoverArtFilename' in s and s['CoverArtFilename'] != None:
542 coverart = THUMB_URL+s['CoverArtFilename'].encode('ascii', 'ignore')
543 else:
544 coverart = 'None'
545 list.append([s['ArtistName'].encode('ascii', 'ignore'),\
546 s['ArtistID'],\
547 s['AlbumName'].encode('ascii', 'ignore'),\
548 s['AlbumID'],\
549 coverart])
550 i = i + 1
551 return list
552 else:
553 return []
554
555 def _parsePlaylists(self, items):
556 if 'result' in items:
557 i = 0
558 list = []
559 playlists = items['result']
560 while(i < len(playlists)):
561 s = playlists[i]
562 list.append([s['Name'].encode('ascii', 'ignore'), s['PlaylistID']])
563 i = i + 1
564 return list
565 else:
566 return []
567
568 # Test
569 #import sys
570 #res = []
571 #groovesharkApi = GrooveAPI()
572 #res = groovesharkApi.pingService()
573 #res = groovesharkApi.login(sys.argv[1], sys.argv[2])
574 #songIDs = ['23404546','23401810','23401157']
575 #res = groovesharkApi.createPlaylist("Test")
576 #res = groovesharkApi.setPlaylistSongs(res, songIDs)
577 #res = groovesharkApi.getPlaylistSongs(42251632)
578 #res = groovesharkApi.getSongSearchResults('jimmy jazz', 3)
579 #res = groovesharkApi.getPopularSongsToday(3)
580 #res = groovesharkApi.getSongURLFromSongID('26579347')
581 #res = groovesharkApi.getAlbumSearchResults('london calling', 3)
582 #res = groovesharkApi.getArtistAlbums('52283')
583 #res = groovesharkApi.getArtistSearchResults('the clash', 3)
584 #res = groovesharkApi.getUserFavoriteSongs()
585 #res = groovesharkApi.getUserPlaylists()
586 #res = groovesharkApi.getSongInfo('27425375')
587 #res = groovesharkApi.getPlaylistSongs(40902662)
588 #res = groovesharkApi.addUserFavoriteSong('27425375')
589 #res = groovesharkApi.logout()
590 #
591 #pprint.pprint(res)