1 import socket
, hmac
, urllib
, urllib2
, pprint
, md5
, re
, sha
, time
, random
, os
, pickle
, uuid
, tempfile
3 SESSION_EXPIRY
= 518400 # 6 days in seconds
6 THUMB_URL
= 'http://beta.grooveshark.com/static/amazonart/'
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"
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"}
25 RE_SESSION
= re
.compile('"sessionID":"\s*?([A-z0-9]+)"')
26 RANDOM_CHARS
= "1234567890abcdef"
34 self
.simplejson
= simplejson
36 self
.cacheDir
= os
.path
.join(tempfile
.gettempdir(), 'groovesong')
37 self
._lastSessionTime
= 0
38 self
.uuid
= self
._getUUID
()
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')
47 print "New GrooveSong session id: " + self
.sessionID
48 self
._setSavedSession
()
50 # The actual call to the API
51 def _callRemote(self
, method
, params
, type="default"):
54 "client": CLIENT_NAME
,
55 "clientRevision": CLIENT_VERSION
,
57 "session": self
.sessionID
},
58 "country": {"IPR":"1021", "ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"},
63 token
= self
._getMethodToken
(method
)
65 raise StandardError("Cannot get token")
67 postData
["header"]["token"] = token
69 url
= SERVICE_URL
+ "?" + method
71 url
= API_URL
+ "?" + method
73 postData
= self
.simplejson
.dumps(postData
)
74 print "GrooveSong URL: " + url
75 request
= urllib2
.Request(url
, postData
, HEADERS
)
77 response
= urllib2
.urlopen(request
).read()
79 response
= self
.simplejson
.loads(response
)
80 print "GrooveSong Response..."
81 pprint
.pprint(response
)
83 raise StandardError("API error: " + response
)
89 raise StandardError("API error: " + response
["fault"]["message"])
91 # Generate a random uuid
93 return str(uuid
.uuid4())
95 # Make a token ready for a request header
96 def _getMethodToken(self
, method
):
97 self
._token
= self
._getCommunicationToken
()
98 if self
._token
== None:
102 while 6 > len(randomChars
):
103 randomChars
= randomChars
+ random
.choice(RANDOM_CHARS
)
105 token
= sha
.new(method
+ ":" + self
._token
+ ":quitStealinMahShit:" + randomChars
).hexdigest()
107 return randomChars
+ token
109 # Generate a communication token
110 def _getCommunicationToken(self
):
111 params
= {"secretKey": self
._getSecretKey
(self
.sessionID
)}
114 "client": CLIENT_NAME
,
115 "clientRevision": CLIENT_VERSION
,
117 "session": self
.sessionID
},
118 "country": {"IPR":"1021", "ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"},
120 "parameters": params
,
121 "method": "getCommunicationToken"}
123 postData
= self
.simplejson
.dumps(postData
)
124 request
= urllib2
.Request(TOKEN_URL
, postData
, HEADERS
)
125 response
= urllib2
.urlopen(request
).read()
127 response
= self
.simplejson
.loads(response
)
129 raise StandardError("API error: " + response
)
133 return response
["result"]
137 # Generate a secret key from a sessionID
138 def _getSecretKey(self
, sessionID
):
139 return md5
.new(sessionID
).hexdigest()
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
)
146 self
._lastSessionTime
= time
.time()
147 return session
.group(1)
151 def _getSavedSession(self
):
152 path
= os
.path
.join(self
.cacheDir
, 'session.dmp')
155 session
= pickle
.load(f
)
156 self
.sessionID
= session
['sessionID']
157 self
._lastSessionTime
= session
['lastSessionTime']
161 self
._lastSessionTime
= 0
164 def _setSavedSession(self
):
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')
171 session
= {'sessionID' : self
.sessionID
, 'lastSessionTime' : self
._lastSessionTime
}
172 pickle
.dump(session
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
175 print "An error occurred during save session"
178 # Gets a stream key and host to get song content
179 def _getStreamDetails(self
, songID
):
184 "country": {"IPR":"1021","ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"}
186 response
= self
._callRemote
("getStreamKeyFromSongIDEx", params
)
188 self
._lastStreamKey
= response
["result"]["streamKey"]
189 self
._lastStreamServer
= response
["result"]["ip"]
190 self
._lastStreamServerID
= response
["result"]["streamServerID"]
195 # Tells Grooveshark you have downloaded a song
196 def _markSongDownloaded(self
, songID
):
198 "streamKey": self
._lastStreamKey
,
199 "streamServerID": self
._lastStreamServerID
,
201 self
._callRemote
("markSongDownloaded", params
)
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
)
217 host
= 'api.grooveshark.com'
224 self
.simplejson
= simplejson
225 socket
.setdefaulttimeout(40)
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
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')
239 print "New GrooveAPI session id: " + self
.sessionID
240 self
._setSavedSession
()
243 def _keySort(self
, d
):
244 return [(k
,d
[k
]) for k
in sorted(d
.keys())]
247 def _createMessageSig(self
, method
, params
, secret
):
248 args
= self
._keySort
(params
);
255 h
= hmac
.new(secret
, data
)
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'))
262 req
= urllib2
.Request(url
)
263 response
= urllib2
.urlopen(req
)
264 result
= response
.read()
266 pprint
.pprint(result
)
269 result
= self
.simplejson
.loads(result
)
275 def _getSessionID(self
):
277 result
= self
._callRemote
('startSession', params
)
278 self
.lastSessionTime
= time
.time()
279 return result
['result']['sessionID']
281 def _getSavedSession(self
):
282 path
= os
.path
.join(self
.cacheDir
, 'session.dmp')
285 session
= pickle
.load(f
)
286 self
.sessionID
= session
['sessionID']
287 self
.lastSessionTime
= session
['lastSessionTime']
288 self
.userID
= session
['userID']
292 self
.lastSessionTime
= 0
296 def _setSavedSession(self
):
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')
303 session
= { 'sessionID' : self
.sessionID
, 'lastSessionTime' : self
.lastSessionTime
, 'userID': self
.userID
}
304 pickle
.dump(session
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
307 print "An error occurred during save session"
310 # Make user authentication token
311 def _getUserToken(self
, username
, password
):
312 return md5
.new(username
.lower() + md5
.new(password
).hexdigest()).hexdigest()
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']
321 def login(self
, username
, password
):
324 self
._getSavedSession
()
326 token
= self
._getUserToken
(username
, password
)
327 self
.userID
= self
._authenticateUser
(username
, token
)
329 self
._setSavedSession
()
334 result
= self
._callRemote
('logout', {'sessionID' : self
.sessionID
})
335 if 'result' in result
and result
['result']['success'] == True:
337 self
._setSavedSession
()
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
)
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
)
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
)
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
)
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
)
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
)
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
)
398 # Gets the favorite songs of the logged-in user
399 def getUserFavoriteSongs(self
):
400 if (self
.userID
== 0):
402 result
= self
._callRemote
('getUserFavoriteSongs', {'sessionID' : self
.sessionID
})
403 if 'result' in result
:
404 return self
._parseSongs
(result
)
408 # Add song to user favorites
409 def addUserFavoriteSong(self
, songID
):
410 if (self
.userID
== 0):
412 result
= self
._callRemote
('addUserFavoriteSong', {'sessionID' : self
.sessionID
, 'songID' : songID
})
413 return result
['result']['success']
415 # Get the url to link to a song on Grooveshark
416 def getSongURLFromSongID(self
, songID
):
418 url
= song
.getSongURL(songID
)
419 print "Got song URL " + url
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')
430 info
['CoverArtFilename'] = 'None'
435 # Gets the playlists of the logged-in user
436 def getUserPlaylists(self
):
437 if (self
.userID
== 0):
439 result
= self
._callRemote
('getUserPlaylists', {'sessionID' : self
.sessionID
})
440 if 'result' in result
:
441 return self
._parsePlaylists
(result
)
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']
453 # Gets the playlists of the logged-in user
454 def getUserPlaylistsEx(self
, username
):
455 userID
= self
._getUserIDFromUsername
(username
)
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
)
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
:
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:
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
)
489 def pingService(self
,):
490 result
= self
._callRemote
('pingService', {});
491 if 'result' in result
and result
['result'] != '':
497 def _parseSongs(self
, items
, limit
=0):
498 if 'result' in items
:
504 if 'songs' in items
['result'][0]:
505 l
= len(items
['result'][0]['songs'])
509 if l
< 0 and 'songs' in items
['result']:
510 l
= len(items
['result']['songs'])
514 if l
< 0 and 'song' in items
['result']:
520 l
= len(items
['result'])
523 if limit
> 0 and l
> limit
:
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
]
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')
541 list.append([s
['SongName'].encode('ascii', 'ignore'),\
543 s
['AlbumName'].encode('ascii', 'ignore'),\
545 s
['ArtistName'].encode('ascii', 'ignore'),\
553 # Extract artist data
554 def _parseArtists(self
, items
):
555 if 'result' in items
:
558 artists
= items
['result']['artists']
559 while(i
< len(artists
)):
561 list.append([s
['ArtistName'].encode('ascii', 'ignore'),\
569 def _parseAlbums(self
, items
, limit
=0):
570 if 'result' in items
:
574 albums
= items
['result']['albums']
576 res
= items
['result'][0]
577 albums
= res
['albums']
579 if limit
> 0 and l
> limit
:
583 if 'CoverArtFilename' in s
and s
['CoverArtFilename'] != None:
584 coverart
= THUMB_URL
+s
['CoverArtFilename'].encode('ascii', 'ignore')
587 list.append([s
['ArtistName'].encode('ascii', 'ignore'),\
589 s
['AlbumName'].encode('ascii', 'ignore'),\
597 def _parsePlaylists(self
, items
):
600 if 'result' in items
:
601 playlists
= items
['result']
607 while (i
< len(playlists
)):
609 list.append([s
['Name'].encode('ascii', 'ignore'), s
['PlaylistID']])
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')