a20592465c3e88c04a9dcf2b12ffa3ac402a84d0
1 import socket
, hmac
, urllib
, urllib2
, pprint
, md5
, re
, sha
, time
, random
, os
, pickle
, uuid
, tempfile
, pprint
3 SESSION_EXPIRY
= 518400 # 6 days in seconds
6 THUMB_URL
= 'http://beta.grooveshark.com/static/amazonart/m'
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
)
214 def __init__(self
, sessionID
= 0):
216 self
.simplejson
= simplejson
218 socket
.setdefaulttimeout(timeout
)
221 self
.sessionID
= sessionID
223 def callRemote(self
, method
, params
={}):
224 data
= {'header': {'sessionID': self
.sessionID
}, 'method': method
, 'parameters': params
}
225 data
= self
.simplejson
.dumps(data
)
226 req
= urllib2
.Request("http://api.grooveshark.com/ws/1.0/?json")
227 req
.add_header('Host', 'api.grooveshark.com')
228 req
.add_header('Content-type', 'text/json')
229 req
.add_header('Content-length', str(len(data
)))
231 response
= urllib2
.urlopen(req
)
232 result
= response
.read()
235 result
= self
.simplejson
.loads(result
)
236 if 'fault' in result
:
237 if result
['fault']['code'] == 8: #Session ID has expired. Get a new and try again if possible.
238 print 'GrooveShark: SessionID expired'
244 def login(self
, username
, password
):
245 if self
.loggedIn
== 1:
247 token
= md5
.new(username
.lower() + md5
.new(password
).hexdigest()).hexdigest()
248 result
= self
.callRemote("session.loginExt", {"username": username
, "token": token
})
249 if 'result' in result
:
250 if 'userID' in result
['result']:
252 self
.userId
= result
['result']['userID']
253 return result
['result']['userID']
257 def unfavorite(self
, songID
):
258 return self
.callRemote("song.unfavorite", {"songID": songID
})
260 def playlistCreate(self
, name
, about
):
261 if self
.loggedIn
== 1:
262 result
= self
.callRemote("playlist.create", {"name": name
, "about": about
})
263 if 'result' in result
:
264 return result
['result']['playlistID']
270 def playlistCreateUnique(self
, name
, songIds
):
271 if self
.loggedIn
== 1:
272 result
= self
.callRemote("playlist.createunique", {"name": name
, "songIDs": songIds
})
273 if 'result' in result
:
274 return result
['result']['playlistID']
280 def playlistDelete(self
, playlistId
):
281 if self
.loggedIn
== 1:
282 result
= self
.callRemote("playlist.delete", {"playlistID": playlistId
})
283 if 'fault' in result
:
290 def playlistRename(self
, playlistId
, name
):
291 if self
.loggedIn
== 1:
292 result
= self
.callRemote("playlist.rename", {"playlistID": playlistId
, "name": name
})
293 if 'fault' in result
:
300 def playlistClearSongs(self
, playlistId
):
301 if self
.loggedIn
== 1:
302 return self
.callRemote("playlist.clearSongs", {"playlistID": playlistId
})
304 def playlistAddSong(self
, playlistId
, songId
, position
):
305 if self
.loggedIn
== 1:
306 result
= self
.callRemote("playlist.addSong", {"playlistID": playlistId
, "songID": songId
, "position": position
})
307 if 'fault' in result
:
314 def playlistDeleteSong(self
, playlistId
, position
):
315 if self
.loggedIn
== 1:
316 result
= self
.callRemote("playlist.removeSong", {"playlistID": playlistId
, "position": position
})
317 if 'fault' in result
:
324 def playlistReplace(self
, playlistId
, songIds
):
325 if self
.loggedIn
== 1:
326 result
= self
.callRemote("playlist.replace", {"playlistID": playlistId
, "songIDs": songIds
})
327 if 'fault' in result
:
334 def artistGetSimilar(self
, artistId
, limit
):
335 items
= self
.callRemote("artist.getSimilar", {"artistID": artistId
, "limit": limit
})
336 if 'result' in items
:
339 artists
= items
['result']['artists']
340 while(i
< len(artists
)):
342 list.append([s
['artistName'].encode('ascii', 'ignore'),\
354 host
= 'api.grooveshark.com'
361 self
.simplejson
= simplejson
362 socket
.setdefaulttimeout(40)
364 self
.cacheDir
= os
.path
.join(tempfile
.gettempdir(), 'grooveapi')
365 if os
.path
.isdir(self
.cacheDir
) == False:
366 os
.makedirs(self
.cacheDir
)
367 print "Made " + self
.cacheDir
369 self
._getSavedSession
()
370 # session ids last 1 week
371 if self
.sessionID
== '' or time
.time()- self
.lastSessionTime
>= SESSION_EXPIRY
:
372 self
.sessionID
= self
._getSessionID
()
373 if self
.sessionID
== '':
374 raise StandardError('Failed to get session id')
376 print "New GrooveAPI session id: " + self
.sessionID
377 self
._setSavedSession
()
380 def _keySort(self
, d
):
381 return [(k
,d
[k
]) for k
in sorted(d
.keys())]
384 def _createMessageSig(self
, method
, params
, secret
):
385 args
= self
._keySort
(params
);
392 h
= hmac
.new(secret
, data
)
395 # The actual call to the API
396 def _callRemote(self
, method
, params
= {}):
397 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'))
399 req
= urllib2
.Request(url
)
400 response
= urllib2
.urlopen(req
)
401 result
= response
.read()
403 pprint
.pprint(result
)
406 result
= self
.simplejson
.loads(result
)
412 def _getSessionID(self
):
414 result
= self
._callRemote
('startSession', params
)
415 self
.lastSessionTime
= time
.time()
416 return result
['result']['sessionID']
418 def _getSavedSession(self
):
419 path
= os
.path
.join(self
.cacheDir
, 'session.dmp')
422 session
= pickle
.load(f
)
423 self
.sessionID
= session
['sessionID']
424 self
.lastSessionTime
= session
['lastSessionTime']
425 self
.userID
= session
['userID']
429 self
.lastSessionTime
= 0
433 def _setSavedSession(self
):
435 # Create the directory if it doesn't exist.
436 if not os
.path
.exists(self
.cacheDir
):
437 os
.makedirs(self
.cacheDir
)
438 path
= os
.path
.join(self
.cacheDir
, 'session.dmp')
440 session
= { 'sessionID' : self
.sessionID
, 'lastSessionTime' : self
.lastSessionTime
, 'userID': self
.userID
}
441 pickle
.dump(session
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
444 print "An error occurred during save session"
447 # Make user authentication token
448 def _getUserToken(self
, username
, password
):
449 return md5
.new(username
.lower() + md5
.new(password
).hexdigest()).hexdigest()
451 # Authenticates the user for current API session
452 def _authenticateUser(self
, username
, token
):
453 params
= {'sessionID': self
.sessionID
, 'username': username
, 'token': token
}
454 result
= self
._callRemote
('authenticateUser', params
)
455 return result
['result']['UserID']
458 def login(self
, username
, password
):
461 self
._getSavedSession
()
463 token
= self
._getUserToken
(username
, password
)
464 self
.userID
= self
._authenticateUser
(username
, token
)
466 self
._setSavedSession
()
471 result
= self
._callRemote
('logout', {'sessionID' : self
.sessionID
})
472 if 'result' in result
and result
['result']['success'] == True:
474 self
._setSavedSession
()
479 def getArtistSearchResults(self
, query
, limit
=ARTIST_LIMIT
):
480 result
= self
._callRemote
('getArtistSearchResults', {'query' : query
,'limit' : limit
})
481 if 'result' in result
:
482 return self
._parseArtists
(result
)
487 def getAlbumSearchResults(self
, query
, limit
=ALBUM_LIMIT
):
488 result
= self
._callRemote
('getAlbumSearchResults', {'query' : query
,'limit' : limit
})
489 if 'result' in result
:
490 return self
._parseAlbums
(result
)
495 def getSongSearchResults(self
, query
, limit
=SONG_LIMIT
):
496 result
= self
._callRemote
('getSongSearchResultsEx', {'query' : query
, 'limit' : limit
})
497 if 'result' in result
:
498 return self
._parseSongs
(result
)
503 def getArtistAlbums(self
, artistID
, limit
=ALBUM_LIMIT
):
504 result
= self
._callRemote
('getArtistAlbums', {'artistID' : artistID
})
505 if 'result' in result
:
506 return self
._parseAlbums
(result
, limit
)
511 def getAlbumSongs(self
, albumID
, limit
=SONG_LIMIT
):
512 result
= self
._callRemote
('getAlbumSongsEx', {'albumID' : albumID
, 'limit' : limit
})
513 if 'result' in result
:
514 return self
._parseSongs
(result
)
518 # Get artist's popular songs
519 def getArtistPopularSongs(self
, artistID
, limit
= SONG_LIMIT
):
520 result
= self
._callRemote
('getArtistPopularSongs', {'artistID' : artistID
})
521 if 'result' in result
:
522 return self
._parseSongs
(result
, limit
)
526 # Gets the popular songs
527 def getPopularSongsToday(self
, limit
=SONG_LIMIT
):
528 result
= self
._callRemote
('getPopularSongsToday', {'limit' : limit
})
529 if 'result' in result
:
530 # Note limit is broken in the Grooveshark getPopularSongsToday method
531 return self
._parseSongs
(result
, limit
)
535 # Gets the favorite songs of the logged-in user
536 def getUserFavoriteSongs(self
):
537 if (self
.userID
== 0):
539 result
= self
._callRemote
('getUserFavoriteSongs', {'sessionID' : self
.sessionID
})
540 if 'result' in result
:
541 return self
._parseSongs
(result
)
545 # Add song to user favorites
546 def addUserFavoriteSong(self
, songID
):
547 if (self
.userID
== 0):
549 result
= self
._callRemote
('addUserFavoriteSong', {'sessionID' : self
.sessionID
, 'songID' : songID
})
550 return result
['result']['success']
552 # Get the url to link to a song on Grooveshark
553 def getSongURLFromSongID(self
, songID
):
555 url
= song
.getSongURL(songID
)
556 print "Got song URL " + url
559 # Get the url to link to a song on Grooveshark
560 def getSongInfo(self
, songID
):
561 result
= self
._callRemote
('getSongInfoEx', {'songID' : songID
})
562 if 'result' in result
and 'SongID' in result
['result']:
563 info
= result
['result']
564 if 'CoverArtFilename' in info
and info
['CoverArtFilename'] != None:
565 info
['CoverArtFilename'] = THUMB_URL
+info
['CoverArtFilename'].encode('ascii', 'ignore')
567 info
['CoverArtFilename'] = 'None'
572 # Gets the playlists of the logged-in user
573 def getUserPlaylists(self
):
574 if (self
.userID
== 0):
576 result
= self
._callRemote
('getUserPlaylists', {'sessionID' : self
.sessionID
})
577 if 'result' in result
:
578 return self
._parsePlaylists
(result
)
582 # Get userid from name
583 def _getUserIDFromUsername(self
, username
):
584 result
= self
._callRemote
('getUserIDFromUsername', {'username' : username
})
585 if 'result' in result
and result
['result']['UserID'] > 0:
586 return result
['result']['UserID']
590 # Gets the playlists of the logged-in user
591 def getUserPlaylistsEx(self
, username
):
592 userID
= self
._getUserIDFromUsername
(username
)
594 result
= self
._callRemote
('getUserPlaylistsEx', {'userID' : userID
})
595 if 'result' in result
and result
['result']['playlists'] != None:
596 playlists
= result
['result']['playlists']
597 return self
._parsePlaylists
(playlists
)
601 # Creates a playlist with songs
602 def createPlaylist(self
, name
, songIDs
):
603 result
= self
._callRemote
('createPlaylist', {'name' : name
, 'songIDs' : songIDs
, 'sessionID' : self
.sessionID
})
604 if 'result' in result
and result
['result']['success'] == True:
605 return result
['result']['playlistID']
606 elif 'errors' in result
:
609 # Sets the songs for a playlist
610 def setPlaylistSongs(self
, playlistID
, songIDs
):
611 result
= self
._callRemote
('setPlaylistSongs', {'playlistID' : playlistID
, 'songIDs' : songIDs
, 'sessionID' : self
.sessionID
})
612 if 'result' in result
and result
['result']['success'] == True:
617 # Gets the songs of a playlist
618 def getPlaylistSongs(self
, playlistID
):
619 result
= self
._callRemote
('getPlaylistSongs', {'playlistID' : playlistID
});
620 if 'result' in result
:
621 return self
._parseSongs
(result
)
626 def pingService(self
,):
627 result
= self
._callRemote
('pingService', {});
628 if 'result' in result
and result
['result'] != '':
634 def _parseSongs(self
, items
, limit
=0):
635 if 'result' in items
:
641 if 'songs' in items
['result'][0]:
642 l
= len(items
['result'][0]['songs'])
646 if l
< 0 and 'songs' in items
['result']:
647 l
= len(items
['result']['songs'])
651 if l
< 0 and 'song' in items
['result']:
657 l
= len(items
['result'])
660 if limit
> 0 and l
> limit
:
663 if index
== 'songs[]':
664 s
= items
['result'][0]['songs'][i
]
665 elif index
== 'songs':
666 s
= items
['result'][index
][i
]
667 elif index
== 'song':
668 s
= items
['result'][index
]
670 s
= items
['result'][i
]
671 if 'CoverArtFilename' not in s
:
672 info
= self
.getSongInfo(s
['SongID'])
673 coverart
= info
['CoverArtFilename']
674 elif s
['CoverArtFilename'] != None:
675 coverart
= THUMB_URL
+s
['CoverArtFilename'].encode('ascii', 'ignore')
678 list.append([s
['SongName'].encode('ascii', 'ignore'),\
680 s
['AlbumName'].encode('ascii', 'ignore'),\
682 s
['ArtistName'].encode('ascii', 'ignore'),\
690 # Extract artist data
691 def _parseArtists(self
, items
):
692 if 'result' in items
:
695 artists
= items
['result']['artists']
696 while(i
< len(artists
)):
698 list.append([s
['ArtistName'].encode('ascii', 'ignore'),\
706 def _parseAlbums(self
, items
, limit
=0):
707 if 'result' in items
:
711 albums
= items
['result']['albums']
713 res
= items
['result'][0]
714 albums
= res
['albums']
716 if limit
> 0 and l
> limit
:
720 if 'CoverArtFilename' in s
and s
['CoverArtFilename'] != None:
721 coverart
= THUMB_URL
+s
['CoverArtFilename'].encode('ascii', 'ignore')
724 list.append([s
['ArtistName'].encode('ascii', 'ignore'),\
726 s
['AlbumName'].encode('ascii', 'ignore'),\
734 def _parsePlaylists(self
, items
):
737 if 'result' in items
:
738 playlists
= items
['result']
744 while (i
< len(playlists
)):
746 list.append([s
['Name'].encode('ascii', 'ignore'), s
['PlaylistID']])
753 #groovesharkApi = GrooveAPI()
754 #res = groovesharkApi.pingService()
755 #res = groovesharkApi.login(sys.argv[1], sys.argv[2])
756 #songIDs = "[23404546,23401810,23401157]"
757 #res = groovesharkApi.createPlaylist("Test", songIDs)
758 #res = groovesharkApi.setPlaylistSongs('42873478', songIDs)
760 #res = groovesharkApi.getPlaylistSongs('42873478')
761 #res = groovesharkApi.getSongSearchResults('jimmy jazz', 3)
762 #res = groovesharkApi.getPopularSongsToday(3)
763 #res = groovesharkApi.getSongURLFromSongID('26579347')
764 #res = groovesharkApi.getAlbumSearchResults('london calling', 3)
765 #res = groovesharkApi.getArtistAlbums('52283')
766 #res = groovesharkApi.getArtistSearchResults('the clash', 3)
767 #res = groovesharkApi.getUserFavoriteSongs()
768 #res = groovesharkApi.getUserPlaylists()
769 #res = groovesharkApi.getSongInfo('27425375')
770 #res = groovesharkApi.getPlaylistSongs(40902662)
771 #res = groovesharkApi.addUserFavoriteSong('27425375')
772 #res = groovesharkApi.logout()
773 #res = groovesharkApi.getUserPlaylistsEx('stephendenham')
774 #res = groovesharkApi.getArtistPopularSongs('3707')