1 # Copyright 2011 Stephen Denham
3 # This file is part of xbmc-groove.
5 # xbmc-groove is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
10 # xbmc-groove is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with xbmc-groove. If not, see <http://www.gnu.org/licenses/>.
18 import urllib2
, pprint
, md5
, os
, pickle
, tempfile
, time
, re
, simplejson
, base64
19 from blowfish
import Blowfish
21 SESSION_EXPIRY
= 1209600 # 2 weeks
24 WEB_APP_URL
= "http://xbmc-groove.appspot.com/"
27 THUMB_URL
= 'http://beta.grooveshark.com/static/amazonart/m'
42 _lastStreamServerID
= ''
43 _key
= md5
.new(os
.path
.basename("GroovesharkAPI.py")).hexdigest()
48 self
.simplejson
= simplejson
49 self
.cacheDir
= os
.path
.join(tempfile
.gettempdir(), 'groovesharkapi')
50 if os
.path
.isdir(self
.cacheDir
) == False:
51 os
.makedirs(self
.cacheDir
)
52 print "Made " + self
.cacheDir
53 self
._getSavedSession
()
54 # session ids last 2 weeks
55 if self
._sessionID
== '' or time
.time()- self
._lastSessionTime
>= SESSION_EXPIRY
:
56 self
._sessionID
= self
._getSessionID
()
57 if self
._sessionID
== '':
58 raise StandardError('Failed to get session id')
60 print "New GrooveAPI session id: " + self
._sessionID
61 self
._ip
= self
._getIP
()
62 self
._country
= self
._getCountry
()
63 self
._setSavedSession
()
66 def _callRemote(self
, method
, params
):
68 res
= self
._getRemote
(method
, params
)
70 postData
= res
['postData']
72 print "Failed to get request URL and post data"
75 req
= urllib2
.Request(url
, postData
)
76 response
= urllib2
.urlopen(req
)
77 result
= response
.read()
81 result
= simplejson
.loads(result
)
83 except urllib2
.HTTPError
, e
:
84 print "HTTP error " + e
.code
85 except urllib2
.URLError
, e
:
86 print "URL error " + e
.reason
88 print "Request to Grooveshark API failed"
93 def _getRemote(self
, method
, params
= {}):
94 postData
= { "method": method
, "sessionid": self
._sessionID
, "parameters": params
}
95 postData
= simplejson
.dumps(postData
)
97 cipher
= Blowfish(self
._key
)
99 encryptedPostData
= cipher
.encryptCTR(postData
)
100 encryptedPostData
= base64
.urlsafe_b64encode(encryptedPostData
)
101 url
= WEB_APP_URL
+ "?postData=" + encryptedPostData
102 req
= urllib2
.Request(url
)
103 response
= urllib2
.urlopen(req
)
104 result
= response
.read()
106 pprint
.pprint(result
)
109 result
= simplejson
.loads(result
)
115 def _getSessionID(self
):
117 result
= self
._callRemote
('startSession', params
)
118 if 'result' in result
:
119 self
._lastSessionTime
= time
.time()
120 return result
['result']['sessionID']
124 def _getSavedSession(self
):
125 path
= os
.path
.join(self
.cacheDir
, 'session.dmp')
128 session
= pickle
.load(f
)
129 self
._sessionID
= session
['sessionID']
130 self
._lastSessionTime
= session
['lastSessionTime']
131 self
._userID
= session
['userID']
132 self
._ip
= session
['ip']
133 self
._country
= session
['country']
137 self
._lastSessionTime
= 0
143 def _setSavedSession(self
):
145 # Create the directory if it doesn't exist.
146 if not os
.path
.exists(self
.cacheDir
):
147 os
.makedirs(self
.cacheDir
)
148 path
= os
.path
.join(self
.cacheDir
, 'session.dmp')
150 session
= { 'sessionID' : self
._sessionID
, 'lastSessionTime' : self
._lastSessionTime
, 'userID': self
._userID
, 'ip' : self
._ip
, 'country' : self
._country
}
151 pickle
.dump(session
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
154 print "An error occurred during save session"
157 def _setParams(self
, params
):
159 # Create the directory if it doesn't exist.
160 if not os
.path
.exists(self
.cacheDir
):
161 os
.makedirs(self
.cacheDir
)
162 path
= os
.path
.join(self
.cacheDir
, 'params.dmp')
164 pickle
.dump(params
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
167 print "An error occurred during save params"
173 myip
= urllib2
.urlopen('http://whatismyip.org').read()
174 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
):
175 print "IP is " + myip
181 def _getCountry(self
):
182 params
= { 'ip' : self
._ip
}
183 response
= self
._callRemote
("getCountry", params
)
184 return response
['result']
186 # Get userid from name
187 def _getUserIDFromUsername(self
, username
):
188 result
= self
._callRemote
('getUserIDFromUsername', {'username' : username
})
189 if 'result' in result
and result
['result']['UserID'] > 0:
190 return result
['result']['UserID']
194 # Authenticates the user for current API session
195 def _authenticate(self
, login
, password
):
196 md5pwd
= md5
.new(password
).hexdigest()
197 params
= {'login': login
, 'password': md5pwd
}
199 result
= self
._callRemote
('authenticate', params
)
201 uid
= result
['result']['UserID']
210 def pingService(self
,):
211 result
= self
._callRemote
('pingService', {});
212 if 'result' in result
and result
['result'] != '':
218 def login(self
, username
, password
):
219 if self
._userID
<= 0:
221 self
._getSavedSession
()
222 if self
._userID
<= 0:
223 self
._userID
= self
._authenticate
(username
, password
)
225 self
._setSavedSession
()
230 result
= self
._callRemote
('logout', {'sessionID' : self
._sessionID
})
231 if 'result' in result
and result
['result']['success'] == True:
233 self
._setSavedSession
()
237 # Gets a stream key and host to get song content
238 def getSubscriberStreamKey(self
, songID
):
239 params
= { "songID": songID
, "country": self
._country
}
240 response
= self
._callRemote
("getSubscriberStreamKey", params
)
242 self
._lastStreamKey
= response
["result"]["StreamKey"]
243 self
._lastStreamServerID
= response
["result"]["StreamServerID"]
244 res
= response
["result"]
250 def getArtistSearchResults(self
, query
, limit
=ARTIST_LIMIT
):
251 result
= self
._callRemote
('getArtistSearchResults', {'query' : query
,'limit' : limit
})
252 if 'result' in result
:
253 return self
._parseArtists
(result
)
258 def getAlbumSearchResults(self
, query
, limit
=ALBUM_LIMIT
):
259 result
= self
._callRemote
('getAlbumSearchResults', {'query' : query
,'limit' : limit
})
260 if 'result' in result
:
261 return self
._parseAlbums
(result
)
266 def getSongSearchResults(self
, query
, limit
=SONG_LIMIT
):
267 result
= self
._callRemote
('getSongSearchResults', {'query' : query
, 'country' : self
._country
, 'limit' : limit
})
268 if 'result' in result
:
269 return self
._parseSongs
(result
)
274 def getArtistAlbums(self
, artistID
, limit
=ALBUM_LIMIT
):
275 result
= self
._callRemote
('getArtistAlbums', {'artistID' : artistID
})
276 if 'result' in result
:
277 return self
._parseAlbums
(result
, limit
)
282 def getAlbumSongs(self
, albumID
, limit
=SONG_LIMIT
):
283 result
= self
._callRemote
('getAlbumSongs', {'albumID' : albumID
, 'limit' : limit
})
284 if 'result' in result
:
285 return self
._parseSongs
(result
)
289 # Get artist's popular songs
290 def getArtistPopularSongs(self
, artistID
, limit
= SONG_LIMIT
):
291 result
= self
._callRemote
('getArtistPopularSongs', {'artistID' : artistID
})
292 if 'result' in result
:
293 return self
._parseSongs
(result
, limit
)
297 # Gets the popular songs
298 def getPopularSongsToday(self
, limit
=SONG_LIMIT
):
299 result
= self
._callRemote
('getPopularSongsToday', {'limit' : limit
})
300 if 'result' in result
:
301 # Note limit is broken in the Grooveshark getPopularSongsToday method
302 return self
._parseSongs
(result
, limit
)
306 # Gets the favorite songs of the logged-in user
307 def getUserFavoriteSongs(self
):
308 if (self
._userID
== 0):
310 result
= self
._callRemote
('getUserFavoriteSongs', {})
311 if 'result' in result
:
312 return self
._parseSongs
(result
)
317 def getSongsInfo(self
, songIDs
):
318 result
= self
._callRemote
('getSongsInfo', {'songIDs' : songIDs
})
319 if 'result' in result
and 'SongID' in result
['result']:
320 info
= result
['result']
321 if 'CoverArtFilename' in info
and info
['CoverArtFilename'] != None:
322 info
['CoverArtFilename'] = THUMB_URL
+info
['CoverArtFilename'].encode('ascii', 'ignore')
324 info
['CoverArtFilename'] = 'None'
329 # Add song to user favorites
330 def addUserFavoriteSong(self
, songID
):
331 if (self
._userID
== 0):
333 result
= self
._callRemote
('addUserFavoriteSong', {'songID' : songID
})
334 return result
['result']['success']
336 # Remove songs from user favorites
337 def removeUserFavoriteSongs(self
, songIDs
):
338 if (self
._userID
== 0):
340 result
= self
._callRemote
('removeUserFavoriteSongs', {'songIDs' : songIDs
})
341 return result
['result']['success']
343 # Gets the playlists of the logged-in user
344 def getUserPlaylists(self
):
345 if (self
._userID
== 0):
347 result
= self
._callRemote
('getUserPlaylists', {})
348 if 'result' in result
:
349 return self
._parsePlaylists
(result
)
353 # Gets the playlists of the logged-in user
354 def getUserPlaylistsByUsername(self
, username
):
355 userID
= self
._getUserIDFromUsername
(username
)
357 result
= self
._callRemote
('getUserPlaylistsByUserID', {'userID' : userID
})
358 if 'result' in result
and result
['result']['playlists'] != None:
359 playlists
= result
['result']['playlists']
360 return self
._parsePlaylists
(playlists
)
364 # Creates a playlist with songs
365 def createPlaylist(self
, name
, songIDs
):
366 result
= self
._callRemote
('createPlaylist', {'name' : name
, 'songIDs' : songIDs
})
367 if 'result' in result
and result
['result']['success'] == True:
368 return result
['result']['playlistID']
369 elif 'errors' in result
:
372 # Sets the songs for a playlist
373 def setPlaylistSongs(self
, playlistID
, songIDs
):
374 result
= self
._callRemote
('setPlaylistSongs', {'playlistID' : playlistID
, 'songIDs' : songIDs
})
375 if 'result' in result
and result
['result']['success'] == True:
380 # Gets the songs of a playlist
381 def getPlaylistSongs(self
, playlistID
):
382 result
= self
._callRemote
('getPlaylistSongs', {'playlistID' : playlistID
});
383 if 'result' in result
:
384 return self
._parseSongs
(result
)
389 def playlistDelete(self
, playlistId
):
390 result
= self
._callRemote
("deletePlaylist", {"playlistID": playlistId
})
391 if 'fault' in result
:
396 def playlistRename(self
, playlistId
, name
):
397 result
= self
._callRemote
("renamePlaylist", {"playlistID": playlistId
, "name": name
})
398 if 'fault' in result
:
403 def getSimilarArtists(self
, artistId
, limit
):
404 items
= self
._callRemote
("getSimilarArtists", {"artistID": artistId
, "limit": limit
})
405 if 'result' in items
:
408 artists
= items
['result']['artists']
409 while(i
< len(artists
)):
411 list.append([s
['artistName'].encode('ascii', 'ignore'),\
418 # After 30s play time
419 def markStreamKeyOver30Secs(self
):
420 params
= { "streamKey" : self
._lastStreamKey
, "streamServerID" : self
._lastStreamServerID
}
421 self
._callRemote
("markStreamKeyOver30Secs", params
)
424 def markSongComplete(self
, songid
):
425 params
= { "songID" : songid
, "streamKey" : self
._lastStreamKey
, "streamServerID" : self
._lastStreamServerID
}
426 self
._callRemote
("markSongComplete", params
)
429 def _parseSongs(self
, items
, limit
=0):
430 if 'result' in items
:
436 if 'songs' in items
['result'][0]:
437 l
= len(items
['result'][0]['songs'])
441 if l
< 0 and 'songs' in items
['result']:
442 l
= len(items
['result']['songs'])
446 if l
< 0 and 'song' in items
['result']:
452 l
= len(items
['result'])
455 if limit
> 0 and l
> limit
:
458 if index
== 'songs[]':
459 s
= items
['result'][0]['songs'][i
]
460 elif index
== 'songs':
461 s
= items
['result'][index
][i
]
462 elif index
== 'song':
463 s
= items
['result'][index
]
465 s
= items
['result'][i
]
466 if 'CoverArtFilename' not in s
:
467 info
= self
.getSongsInfo(s
['SongID'])
468 coverart
= info
['CoverArtFilename']
469 elif s
['CoverArtFilename'] != None:
470 coverart
= THUMB_URL
+s
['CoverArtFilename'].encode('ascii', 'ignore')
473 list.append([s
['SongName'].encode('ascii', 'ignore'),\
475 s
['AlbumName'].encode('ascii', 'ignore'),\
477 s
['ArtistName'].encode('ascii', 'ignore'),\
485 # Extract artist data
486 def _parseArtists(self
, items
):
487 if 'result' in items
:
490 artists
= items
['result']['artists']
491 while(i
< len(artists
)):
493 list.append([s
['ArtistName'].encode('ascii', 'ignore'),\
501 def _parseAlbums(self
, items
, limit
=0):
502 if 'result' in items
:
506 albums
= items
['result']['albums']
508 res
= items
['result'][0]
509 albums
= res
['albums']
511 if limit
> 0 and l
> limit
:
515 if 'CoverArtFilename' in s
and s
['CoverArtFilename'] != None:
516 coverart
= THUMB_URL
+s
['CoverArtFilename'].encode('ascii', 'ignore')
519 list.append([s
['ArtistName'].encode('ascii', 'ignore'),\
521 s
['AlbumName'].encode('ascii', 'ignore'),\
529 def _parsePlaylists(self
, items
):
532 if 'result' in items
:
533 playlists
= items
['result']['playlists']
539 while (i
< len(playlists
)):
541 list.append([str(s
['PlaylistName']).encode('ascii', 'ignore'), s
['PlaylistID']])