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 # 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
)
390 # Gets the favorite songs of the logged-in user
391 def getUserFavoriteSongs(self
):
392 if (self
.userID
== 0):
394 result
= self
._callRemote
('getUserFavoriteSongs', {'sessionID' : self
.sessionID
})
395 if 'result' in result
:
396 return self
._parseSongs
(result
)
400 # Add song to user favorites
401 def addUserFavoriteSong(self
, songID
):
402 if (self
.userID
== 0):
404 result
= self
._callRemote
('addUserFavoriteSong', {'sessionID' : self
.sessionID
, 'songID' : songID
})
405 return result
['result']['success']
407 # Get the url to link to a song on Grooveshark
408 def getSongURLFromSongID(self
, songID
):
410 url
= song
.getSongURL(songID
)
411 print "Got song URL " + url
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')
422 info
['CoverArtFilename'] = 'None'
427 # Gets the playlists of the logged-in user
428 def getUserPlaylists(self
):
429 if (self
.userID
== 0):
431 result
= self
._callRemote
('getUserPlaylists', {'sessionID' : self
.sessionID
})
432 if 'result' in result
:
433 return self
._parsePlaylists
(result
)
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
:
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:
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
)
462 def pingService(self
,):
463 result
= self
._callRemote
('pingService', {});
464 if 'result' in result
and result
['result'] != '':
470 def _parseSongs(self
, items
, limit
=0):
471 if 'result' in items
:
474 if 'songs' in items
['result']:
475 l
= len(items
['result']['songs'])
477 elif 'song' in items
['result']:
481 l
= len(items
['result'])
483 if limit
> 0 and l
> limit
:
487 s
= items
['result'][index
][i
]
488 elif index
== 'song':
489 s
= items
['result'][index
]
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')
499 list.append([s
['SongName'].encode('ascii', 'ignore'),\
501 s
['AlbumName'].encode('ascii', 'ignore'),\
503 s
['ArtistName'].encode('ascii', 'ignore'),\
511 # Extract artist data
512 def _parseArtists(self
, items
):
513 if 'result' in items
:
516 artists
= items
['result']['artists']
517 while(i
< len(artists
)):
519 list.append([s
['ArtistName'].encode('ascii', 'ignore'),\
527 def _parseAlbums(self
, items
, limit
=0):
528 if 'result' in items
:
532 albums
= items
['result']['albums']
534 res
= items
['result'][0]
535 albums
= res
['albums']
537 if limit
> 0 and l
> limit
:
541 if 'CoverArtFilename' in s
and s
['CoverArtFilename'] != None:
542 coverart
= THUMB_URL
+s
['CoverArtFilename'].encode('ascii', 'ignore')
545 list.append([s
['ArtistName'].encode('ascii', 'ignore'),\
547 s
['AlbumName'].encode('ascii', 'ignore'),\
555 def _parsePlaylists(self
, items
):
556 if 'result' in items
:
559 playlists
= items
['result']
560 while(i
< len(playlists
)):
562 list.append([s
['Name'].encode('ascii', 'ignore'), s
['PlaylistID']])
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()