43db1baa794aea6de7cc4d4bc72c9d35a4f6e0c7
1 import socket
, urllib
, urllib2
, pprint
, md5
, os
, pickle
, tempfile
, time
, re
, simplejson
, base64
2 from blowfish
import Blowfish
4 SESSION_EXPIRY
= 1209600 # 2 weeks
7 WEB_APP_URL
= "http://xbmc-groove.appspot.com/"
10 THUMB_URL
= 'http://beta.grooveshark.com/static/amazonart/m'
25 _lastStreamServerID
= ''
26 _key
= md5
.new(os
.path
.basename("GroovesharkAPI.py")).hexdigest()
31 self
.simplejson
= simplejson
32 socket
.setdefaulttimeout(40)
33 self
.cacheDir
= os
.path
.join(tempfile
.gettempdir(), 'groovesharkapi')
34 if os
.path
.isdir(self
.cacheDir
) == False:
35 os
.makedirs(self
.cacheDir
)
36 print "Made " + self
.cacheDir
37 self
._getSavedSession
()
38 # session ids last 2 weeks
39 if self
._sessionID
== '' or time
.time()- self
._lastSessionTime
>= SESSION_EXPIRY
:
40 self
._sessionID
= self
._getSessionID
()
41 if self
._sessionID
== '':
42 raise StandardError('Failed to get session id')
44 print "New GrooveAPI session id: " + self
._sessionID
45 self
._ip
= self
._getIP
()
46 self
._country
= self
._getCountry
()
47 self
._setSavedSession
()
50 def _callRemote(self
, method
, params
):
52 res
= self
._getRemote
(method
, params
)
54 postData
= res
['postData']
56 print "Failed to get request URL and post data"
59 req
= urllib2
.Request(url
, postData
)
60 response
= urllib2
.urlopen(req
)
61 result
= response
.read()
65 result
= simplejson
.loads(result
)
67 except urllib2
.HTTPError
, e
:
68 print "HTTP error " + e
.code
69 except urllib2
.URLError
, e
:
70 print "URL error " + e
.reason
72 print "Request to Grooveshark API failed"
77 def _getRemote(self
, method
, params
= {}):
78 postData
= { "method": method
, "sessionid": self
._sessionID
, "parameters": params
}
79 postData
= simplejson
.dumps(postData
)
81 cipher
= Blowfish(self
._key
)
83 encryptedPostData
= cipher
.encryptCTR(postData
)
84 encryptedPostData
= base64
.urlsafe_b64encode(encryptedPostData
)
85 url
= WEB_APP_URL
+ "?postData=" + encryptedPostData
86 req
= urllib2
.Request(url
)
87 response
= urllib2
.urlopen(req
)
88 result
= response
.read()
93 result
= simplejson
.loads(result
)
99 def _getSessionID(self
):
101 result
= self
._callRemote
('startSession', params
)
102 if 'result' in result
:
103 self
._lastSessionTime
= time
.time()
104 return result
['result']['sessionID']
108 def _getSavedSession(self
):
109 path
= os
.path
.join(self
.cacheDir
, 'session.dmp')
112 session
= pickle
.load(f
)
113 self
._sessionID
= session
['sessionID']
114 self
._lastSessionTime
= session
['lastSessionTime']
115 self
._userID
= session
['userID']
116 self
._ip
= session
['ip']
117 self
._country
= session
['country']
121 self
._lastSessionTime
= 0
127 def _setSavedSession(self
):
129 # Create the directory if it doesn't exist.
130 if not os
.path
.exists(self
.cacheDir
):
131 os
.makedirs(self
.cacheDir
)
132 path
= os
.path
.join(self
.cacheDir
, 'session.dmp')
134 session
= { 'sessionID' : self
._sessionID
, 'lastSessionTime' : self
._lastSessionTime
, 'userID': self
._userID
, 'ip' : self
._ip
, 'country' : self
._country
}
135 pickle
.dump(session
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
138 print "An error occurred during save session"
141 def _setParams(self
, params
):
143 # Create the directory if it doesn't exist.
144 if not os
.path
.exists(self
.cacheDir
):
145 os
.makedirs(self
.cacheDir
)
146 path
= os
.path
.join(self
.cacheDir
, 'params.dmp')
148 pickle
.dump(params
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
151 print "An error occurred during save params"
157 myip
= urllib2
.urlopen('http://whatismyip.org').read()
158 if re
.match("^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$", myip
):
159 print "IP is " + myip
165 def _getCountry(self
):
166 params
= { 'ip' : self
._ip
}
167 response
= self
._callRemote
("getCountry", params
)
168 return response
['result']
170 # Get userid from name
171 def _getUserIDFromUsername(self
, username
):
172 result
= self
._callRemote
('getUserIDFromUsername', {'username' : username
})
173 if 'result' in result
and result
['result']['UserID'] > 0:
174 return result
['result']['UserID']
178 # Authenticates the user for current API session
179 def _authenticate(self
, login
, password
):
180 md5pwd
= md5
.new(password
).hexdigest()
181 params
= {'login': login
, 'password': md5pwd
}
183 result
= self
._callRemote
('authenticate', params
)
185 uid
= result
['result']['UserID']
194 def pingService(self
,):
195 result
= self
._callRemote
('pingService', {});
196 if 'result' in result
and result
['result'] != '':
202 def login(self
, username
, password
):
203 if self
._userID
<= 0:
205 self
._getSavedSession
()
206 if self
._userID
<= 0:
207 self
._userID
= self
._authenticate
(username
, password
)
209 self
._setSavedSession
()
214 result
= self
._callRemote
('logout', {'sessionID' : self
._sessionID
})
215 if 'result' in result
and result
['result']['success'] == True:
217 self
._setSavedSession
()
221 # Gets a stream key and host to get song content
222 def getSubscriberStreamKey(self
, songID
):
223 params
= { "songID": songID
, "country": self
._country
}
224 response
= self
._callRemote
("getSubscriberStreamKey", params
)
226 self
._lastStreamKey
= response
["result"]["StreamKey"]
227 self
._lastStreamServerID
= response
["result"]["StreamServerID"]
228 res
= response
["result"]
234 def getArtistSearchResults(self
, query
, limit
=ARTIST_LIMIT
):
235 result
= self
._callRemote
('getArtistSearchResults', {'query' : query
,'limit' : limit
})
236 if 'result' in result
:
237 return self
._parseArtists
(result
)
242 def getAlbumSearchResults(self
, query
, limit
=ALBUM_LIMIT
):
243 result
= self
._callRemote
('getAlbumSearchResults', {'query' : query
,'limit' : limit
})
244 if 'result' in result
:
245 return self
._parseAlbums
(result
)
250 def getSongSearchResults(self
, query
, limit
=SONG_LIMIT
):
251 result
= self
._callRemote
('getSongSearchResults', {'query' : query
, 'country' : self
._country
, 'limit' : limit
})
252 if 'result' in result
:
253 return self
._parseSongs
(result
)
258 def getArtistAlbums(self
, artistID
, limit
=ALBUM_LIMIT
):
259 result
= self
._callRemote
('getArtistAlbums', {'artistID' : artistID
})
260 if 'result' in result
:
261 return self
._parseAlbums
(result
, limit
)
266 def getAlbumSongs(self
, albumID
, limit
=SONG_LIMIT
):
267 result
= self
._callRemote
('getAlbumSongs', {'albumID' : albumID
, 'limit' : limit
})
268 if 'result' in result
:
269 return self
._parseSongs
(result
)
273 # Get artist's popular songs
274 def getArtistPopularSongs(self
, artistID
, limit
= SONG_LIMIT
):
275 result
= self
._callRemote
('getArtistPopularSongs', {'artistID' : artistID
})
276 if 'result' in result
:
277 return self
._parseSongs
(result
, limit
)
281 # Gets the popular songs
282 def getPopularSongsToday(self
, limit
=SONG_LIMIT
):
283 result
= self
._callRemote
('getPopularSongsToday', {'limit' : limit
})
284 if 'result' in result
:
285 # Note limit is broken in the Grooveshark getPopularSongsToday method
286 return self
._parseSongs
(result
, limit
)
290 # Gets the favorite songs of the logged-in user
291 def getUserFavoriteSongs(self
):
292 if (self
._userID
== 0):
294 result
= self
._callRemote
('getUserFavoriteSongs', {})
295 if 'result' in result
:
296 return self
._parseSongs
(result
)
301 def getSongsInfo(self
, songIDs
):
302 result
= self
._callRemote
('getSongsInfo', {'songIDs' : songIDs
})
303 if 'result' in result
and 'SongID' in result
['result']:
304 info
= result
['result']
305 if 'CoverArtFilename' in info
and info
['CoverArtFilename'] != None:
306 info
['CoverArtFilename'] = THUMB_URL
+info
['CoverArtFilename'].encode('ascii', 'ignore')
308 info
['CoverArtFilename'] = 'None'
313 # Add song to user favorites
314 def addUserFavoriteSong(self
, songID
):
315 if (self
._userID
== 0):
317 result
= self
._callRemote
('addUserFavoriteSong', {'songID' : songID
})
318 return result
['result']['success']
320 # Remove songs from user favorites
321 def removeUserFavoriteSongs(self
, songIDs
):
322 if (self
._userID
== 0):
324 result
= self
._callRemote
('removeUserFavoriteSongs', {'songIDs' : songIDs
})
325 return result
['result']['success']
327 # Gets the playlists of the logged-in user
328 def getUserPlaylists(self
):
329 if (self
._userID
== 0):
331 result
= self
._callRemote
('getUserPlaylists', {})
332 if 'result' in result
:
333 return self
._parsePlaylists
(result
)
337 # Gets the playlists of the logged-in user
338 def getUserPlaylistsByUsername(self
, username
):
339 userID
= self
._getUserIDFromUsername
(username
)
341 result
= self
._callRemote
('getUserPlaylistsByUserID', {'userID' : userID
})
342 if 'result' in result
and result
['result']['playlists'] != None:
343 playlists
= result
['result']['playlists']
344 return self
._parsePlaylists
(playlists
)
348 # Creates a playlist with songs
349 def createPlaylist(self
, name
, songIDs
):
350 result
= self
._callRemote
('createPlaylist', {'name' : name
, 'songIDs' : songIDs
})
351 if 'result' in result
and result
['result']['success'] == True:
352 return result
['result']['playlistID']
353 elif 'errors' in result
:
356 # Sets the songs for a playlist
357 def setPlaylistSongs(self
, playlistID
, songIDs
):
358 result
= self
._callRemote
('setPlaylistSongs', {'playlistID' : playlistID
, 'songIDs' : songIDs
})
359 if 'result' in result
and result
['result']['success'] == True:
364 # Gets the songs of a playlist
365 def getPlaylistSongs(self
, playlistID
):
366 result
= self
._callRemote
('getPlaylistSongs', {'playlistID' : playlistID
});
367 if 'result' in result
:
368 return self
._parseSongs
(result
)
373 def playlistDelete(self
, playlistId
):
374 result
= self
._callRemote
("deletePlaylist", {"playlistID": playlistId
})
375 if 'fault' in result
:
380 def playlistRename(self
, playlistId
, name
):
381 result
= self
._callRemote
("renamePlaylist", {"playlistID": playlistId
, "name": name
})
382 if 'fault' in result
:
387 def getSimilarArtists(self
, artistId
, limit
):
388 items
= self
._callRemote
("getSimilarArtists", {"artistID": artistId
, "limit": limit
})
389 if 'result' in items
:
392 artists
= items
['result']['artists']
393 while(i
< len(artists
)):
395 list.append([s
['artistName'].encode('ascii', 'ignore'),\
402 # After 30s play time
403 def markStreamKeyOver30Secs(self
):
404 params
= { "streamKey" : self
._lastStreamKey
, "streamServerID" : self
._lastStreamServerID
}
405 self
._callRemote
("markStreamKeyOver30Secs", params
)
408 def markSongComplete(self
, songid
):
409 params
= { "songID" : songid
, "streamKey" : self
._lastStreamKey
, "streamServerID" : self
._lastStreamServerID
}
410 self
._callRemote
("markSongComplete", params
)
413 def _parseSongs(self
, items
, limit
=0):
414 if 'result' in items
:
420 if 'songs' in items
['result'][0]:
421 l
= len(items
['result'][0]['songs'])
425 if l
< 0 and 'songs' in items
['result']:
426 l
= len(items
['result']['songs'])
430 if l
< 0 and 'song' in items
['result']:
436 l
= len(items
['result'])
439 if limit
> 0 and l
> limit
:
442 if index
== 'songs[]':
443 s
= items
['result'][0]['songs'][i
]
444 elif index
== 'songs':
445 s
= items
['result'][index
][i
]
446 elif index
== 'song':
447 s
= items
['result'][index
]
449 s
= items
['result'][i
]
450 if 'CoverArtFilename' not in s
:
451 info
= self
.getSongsInfo(s
['SongID'])
452 coverart
= info
['CoverArtFilename']
453 elif s
['CoverArtFilename'] != None:
454 coverart
= THUMB_URL
+s
['CoverArtFilename'].encode('ascii', 'ignore')
457 list.append([s
['SongName'].encode('ascii', 'ignore'),\
459 s
['AlbumName'].encode('ascii', 'ignore'),\
461 s
['ArtistName'].encode('ascii', 'ignore'),\
469 # Extract artist data
470 def _parseArtists(self
, items
):
471 if 'result' in items
:
474 artists
= items
['result']['artists']
475 while(i
< len(artists
)):
477 list.append([s
['ArtistName'].encode('ascii', 'ignore'),\
485 def _parseAlbums(self
, items
, limit
=0):
486 if 'result' in items
:
490 albums
= items
['result']['albums']
492 res
= items
['result'][0]
493 albums
= res
['albums']
495 if limit
> 0 and l
> limit
:
499 if 'CoverArtFilename' in s
and s
['CoverArtFilename'] != None:
500 coverart
= THUMB_URL
+s
['CoverArtFilename'].encode('ascii', 'ignore')
503 list.append([s
['ArtistName'].encode('ascii', 'ignore'),\
505 s
['AlbumName'].encode('ascii', 'ignore'),\
513 def _parsePlaylists(self
, items
):
516 if 'result' in items
:
517 playlists
= items
['result']['playlists']
523 while (i
< len(playlists
)):
525 list.append([str(s
['PlaylistName']).encode('ascii', 'ignore'), s
['PlaylistID']])