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