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
)
203 # Download a song to a temporary file
204 def getSongURL(self
, songID
):
205 filename
= os
.path
.join(self
.cacheDir
, songID
+ SONG_SUFFIX
)
206 print "Caching song " + songID
+ " to " + filename
207 if os
.path
.isfile(filename
) == False:
208 if self
._getStreamDetails
(songID
) == True:
209 postData
= {"streamKey": self
._lastStreamKey
}
210 postData
= urllib
.urlencode(postData
)
211 urllib
.FancyURLopener().retrieve( "http://" + self
._lastStreamServer
+ "/stream.php", filename
, data
=postData
)
212 self
._markSongDownloaded
(songID
)
222 host
= 'api.grooveshark.com'
229 self
.simplejson
= simplejson
230 socket
.setdefaulttimeout(40)
232 self
.cacheDir
= os
.path
.join(tempfile
.gettempdir(), 'grooveapi')
233 if os
.path
.isdir(self
.cacheDir
) == False:
234 os
.makedirs(self
.cacheDir
)
235 print "Made " + self
.cacheDir
237 self
._getSavedSession
()
238 # session ids last 1 week
239 if self
.sessionID
== '' or time
.time()- self
.lastSessionTime
>= SESSION_EXPIRY
:
240 self
.sessionID
= self
._getSessionID
()
241 if self
.sessionID
== '':
242 raise StandardError('Failed to get session id')
244 print "New GrooveAPI session id: " + self
.sessionID
245 self
._setSavedSession
()
248 def _keySort(self
, d
):
249 return [(k
,d
[k
]) for k
in sorted(d
.keys())]
252 def _createMessageSig(self
, method
, params
, secret
):
253 args
= self
._keySort
(params
);
260 h
= hmac
.new(secret
, data
)
263 # The actual call to the API
264 def _callRemote(self
, method
, params
= {}):
265 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'))
267 req
= urllib2
.Request(url
)
268 response
= urllib2
.urlopen(req
)
269 result
= response
.read()
271 pprint
.pprint(result
)
274 result
= self
.simplejson
.loads(result
)
280 def _getSessionID(self
):
282 result
= self
._callRemote
('startSession', params
)
283 self
.lastSessionTime
= time
.time()
284 return result
['result']['sessionID']
286 def _getSavedSession(self
):
287 path
= os
.path
.join(self
.cacheDir
, 'session.dmp')
290 session
= pickle
.load(f
)
291 self
.sessionID
= session
['sessionID']
292 self
.lastSessionTime
= session
['lastSessionTime']
293 self
.userID
= session
['userID']
297 self
.lastSessionTime
= 0
301 def _setSavedSession(self
):
303 # Create the directory if it doesn't exist.
304 if not os
.path
.exists(self
.cacheDir
):
305 os
.makedirs(self
.cacheDir
)
306 path
= os
.path
.join(self
.cacheDir
, 'session.dmp')
308 session
= { 'sessionID' : self
.sessionID
, 'lastSessionTime' : self
.lastSessionTime
, 'userID': self
.userID
}
309 pickle
.dump(session
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
312 print "An error occurred during save session"
315 # Make user authentication token
316 def _getUserToken(self
, username
, password
):
317 return md5
.new(username
.lower() + md5
.new(password
).hexdigest()).hexdigest()
319 # Authenticates the user for current API session
320 def _authenticateUser(self
, username
, token
):
321 params
= {'sessionID': self
.sessionID
, 'username': username
, 'token': token
}
322 result
= self
._callRemote
('authenticateUser', params
)
323 return result
['result']['UserID']
326 def login(self
, username
, password
):
329 self
._getSavedSession
()
331 token
= self
._getUserToken
(username
, password
)
332 self
.userID
= self
._authenticateUser
(username
, token
)
334 self
._setSavedSession
()
339 result
= self
._callRemote
('logout', {'sessionID' : self
.sessionID
})
340 if 'result' in result
and result
['result']['success'] == True:
342 self
._setSavedSession
()
347 def getArtistSearchResults(self
, query
, limit
=ARTIST_LIMIT
):
348 result
= self
._callRemote
('getArtistSearchResults', {'query' : query
,'limit' : limit
})
349 if 'result' in result
:
350 return self
._parseArtists
(result
)
355 def getAlbumSearchResults(self
, query
, limit
=ALBUM_LIMIT
):
356 result
= self
._callRemote
('getAlbumSearchResults', {'query' : query
,'limit' : limit
})
357 if 'result' in result
:
358 return self
._parseAlbums
(result
)
363 def getSongSearchResults(self
, query
, limit
=SONG_LIMIT
):
364 result
= self
._callRemote
('getSongSearchResultsEx', {'query' : query
, 'limit' : limit
})
365 if 'result' in result
:
366 return self
._parseSongs
(result
)
371 def getArtistAlbums(self
, artistID
, limit
=ALBUM_LIMIT
):
372 result
= self
._callRemote
('getArtistAlbums', {'artistID' : artistID
})
373 if 'result' in result
:
374 return self
._parseAlbums
(result
, limit
)
379 def getAlbumSongs(self
, albumID
, limit
=SONG_LIMIT
):
380 result
= self
._callRemote
('getAlbumSongsEx', {'albumID' : albumID
, 'limit' : limit
})
381 if 'result' in result
:
382 return self
._parseSongs
(result
)
386 # Gets the popular songs
387 def getPopularSongsToday(self
, limit
=SONG_LIMIT
):
388 result
= self
._callRemote
('getPopularSongsToday', {'limit' : limit
})
389 if 'result' in result
:
390 # Note limit is broken in the Grooveshark getPopularSongsToday method
391 return self
._parseSongs
(result
, limit
)
395 # Gets the favorite songs of the logged-in user
396 def getUserFavoriteSongs(self
):
397 if (self
.userID
== 0):
399 result
= self
._callRemote
('getUserFavoriteSongs', {'sessionID' : self
.sessionID
})
400 if 'result' in result
:
401 return self
._parseSongs
(result
)
405 # Add song to user favorites
406 def addUserFavoriteSong(self
, songID
):
407 if (self
.userID
== 0):
409 result
= self
._callRemote
('addUserFavoriteSong', {'sessionID' : self
.sessionID
, 'songID' : songID
})
410 return result
['result']['success']
412 # Get the url to link to a song on Grooveshark
413 def getSongURLFromSongID(self
, songID
):
415 return song
.getSongURL(songID
)
417 # Get the url to link to a song on Grooveshark
418 def getSongInfo(self
, songID
):
419 result
= self
._callRemote
('getSongInfoEx', {'songID' : songID
})
420 if 'result' in result
and 'SongID' in result
['result']:
421 info
= result
['result']
422 if 'CoverArtFilename' in info
and info
['CoverArtFilename'] != None:
423 info
['CoverArtFilename'] = THUMB_URL
+info
['CoverArtFilename'].encode('ascii', 'ignore')
425 info
['CoverArtFilename'] = 'None'
430 # Gets the playlists of the logged-in user
431 def getUserPlaylists(self
):
432 if (self
.userID
== 0):
434 result
= self
._callRemote
('getUserPlaylists', {'sessionID' : self
.sessionID
})
435 if 'result' in result
:
436 return self
._parsePlaylists
(result
)
440 # Creates a playlist with songs
441 def createPlaylist(self
, name
, songIDs
):
442 result
= self
._callRemote
('createPlaylist', {'name' : name
, 'songIDs' : songIDs
, 'sessionID' : self
.sessionID
})
443 if 'result' in result
and result
['result']['success'] == True:
444 return result
['result']['playlistID']
445 elif 'errors' in result
:
448 # Sets the songs for a playlist
449 def setPlaylistSongs(self
, playlistID
, songIDs
):
450 result
= self
._callRemote
('setPlaylistSongs', {'playlistID' : playlistID
, 'songIDs' : songIDs
, 'sessionID' : self
.sessionID
})
451 if 'result' in result
and result
['result']['success'] == True:
456 # Gets the songs of a playlist
457 def getPlaylistSongs(self
, playlistID
):
458 result
= self
._callRemote
('getPlaylistSongs', {'playlistID' : playlistID
});
459 if 'result' in result
:
460 return self
._parseSongs
(result
)
465 def pingService(self
,):
466 result
= self
._callRemote
('pingService', {});
467 if 'result' in result
and result
['result'] != '':
473 def _parseSongs(self
, items
, limit
=0):
474 if 'result' in items
:
477 if 'songs' in items
['result']:
478 l
= len(items
['result']['songs'])
480 elif 'song' in items
['result']:
484 l
= len(items
['result'])
486 if limit
> 0 and l
> limit
:
490 s
= items
['result'][index
][i
]
491 elif index
== 'song':
492 s
= items
['result'][index
]
494 s
= items
['result'][i
]
495 if 'CoverArtFilename' not in s
:
496 info
= self
.getSongInfo(s
['SongID'])
497 coverart
= info
['CoverArtFilename']
498 elif s
['CoverArtFilename'] != None:
499 coverart
= THUMB_URL
+s
['CoverArtFilename'].encode('ascii', 'ignore')
502 list.append([s
['SongName'].encode('ascii', 'ignore'),\
504 s
['AlbumName'].encode('ascii', 'ignore'),\
506 s
['ArtistName'].encode('ascii', 'ignore'),\
514 # Extract artist data
515 def _parseArtists(self
, items
):
516 if 'result' in items
:
519 artists
= items
['result']['artists']
520 while(i
< len(artists
)):
522 list.append([s
['ArtistName'].encode('ascii', 'ignore'),\
530 def _parseAlbums(self
, items
, limit
=0):
531 if 'result' in items
:
535 albums
= items
['result']['albums']
537 res
= items
['result'][0]
538 albums
= res
['albums']
540 if limit
> 0 and l
> limit
:
544 if 'CoverArtFilename' in s
and s
['CoverArtFilename'] != None:
545 coverart
= THUMB_URL
+s
['CoverArtFilename'].encode('ascii', 'ignore')
548 list.append([s
['ArtistName'].encode('ascii', 'ignore'),\
550 s
['AlbumName'].encode('ascii', 'ignore'),\
558 def _parsePlaylists(self
, items
):
559 if 'result' in items
:
562 playlists
= items
['result']
563 while(i
< len(playlists
)):
565 list.append([s
['Name'].encode('ascii', 'ignore'), s
['PlaylistID']])
574 #groovesharkApi = GrooveAPI()
575 #res = groovesharkApi.pingService()
576 #res = groovesharkApi.login(sys.argv[1], sys.argv[2])
577 #songIDs = ['23404546','23401810','23401157']
578 #res = groovesharkApi.createPlaylist("Test")
579 #res = groovesharkApi.setPlaylistSongs(res, songIDs)
580 #res = groovesharkApi.getPlaylistSongs(42251632)
581 #res = groovesharkApi.getSongSearchResults('jimmy jazz', 3)
582 #res = groovesharkApi.getPopularSongsToday(3)
583 #res = groovesharkApi.getSongURLFromSongID('26579347')
584 #res = groovesharkApi.getAlbumSearchResults('london calling', 3)
585 #res = groovesharkApi.getArtistAlbums('52283')
586 #res = groovesharkApi.getArtistSearchResults('the clash', 3)
587 #res = groovesharkApi.getUserFavoriteSongs()
588 #res = groovesharkApi.getUserPlaylists()
589 #res = groovesharkApi.getSongInfo('27425375')
590 #res = groovesharkApi.getPlaylistSongs(40902662)
591 #res = groovesharkApi.addUserFavoriteSong('27425375')
592 #res = groovesharkApi.logout()