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
, sys
, socket
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'
41 _key
= md5
.new(os
.path
.basename("GroovesharkAPI.py")).hexdigest()
45 def __init__(self
, debug
):
47 self
._debugging
= debug
48 self
.simplejson
= simplejson
49 if "linux" in sys
.platform
.lower():
50 socket
.setdefaulttimeout(30)
52 self
.cacheDir
= os
.path
.join(tempfile
.gettempdir(), 'groovesharkapi')
53 if os
.path
.isdir(self
.cacheDir
) == False:
54 os
.makedirs(self
.cacheDir
)
56 print "Made " + self
.cacheDir
57 self
._getSavedSession
()
58 # session ids last 2 weeks
59 if self
._sessionID
== '' or time
.time()- self
._lastSessionTime
>= SESSION_EXPIRY
:
60 self
._sessionID
= self
._getSessionID
()
61 if self
._sessionID
== '':
62 raise StandardError('Failed to get session id')
65 print "New GrooveAPI session id: " + self
._sessionID
66 self
._ip
= self
._getIP
()
67 self
._country
= self
._getCountry
()
68 self
._setSavedSession
()
71 def _callRemote(self
, method
, params
):
73 res
= self
._getRemote
(method
, params
)
75 postData
= res
['postData']
77 print "Failed to get request URL and post data"
80 req
= urllib2
.Request(url
, postData
)
81 response
= urllib2
.urlopen(req
)
82 result
= response
.read()
87 result
= simplejson
.loads(result
)
89 except urllib2
.HTTPError
, e
:
90 print "HTTP error " + e
.code
91 except urllib2
.URLError
, e
:
92 print "URL error " + e
.reason
94 print "Request to Grooveshark API failed"
99 def _getRemote(self
, method
, params
= {}):
100 postData
= { "method": method
, "sessionid": self
._sessionID
, "parameters": params
}
101 postData
= simplejson
.dumps(postData
)
103 cipher
= Blowfish(self
._key
)
105 encryptedPostData
= cipher
.encryptCTR(postData
)
106 encryptedPostData
= base64
.urlsafe_b64encode(encryptedPostData
)
107 url
= WEB_APP_URL
+ "?postData=" + encryptedPostData
108 req
= urllib2
.Request(url
)
109 response
= urllib2
.urlopen(req
)
110 result
= response
.read()
113 pprint
.pprint(result
)
116 result
= simplejson
.loads(result
)
122 def _getSessionID(self
):
124 result
= self
._callRemote
('startSession', params
)
125 if 'result' in result
:
126 self
._lastSessionTime
= time
.time()
127 return result
['result']['sessionID']
131 def _getSavedSession(self
):
132 path
= os
.path
.join(self
.cacheDir
, 'session.dmp')
135 session
= pickle
.load(f
)
136 self
._sessionID
= session
['sessionID']
137 self
._lastSessionTime
= session
['lastSessionTime']
138 self
._userID
= session
['userID']
139 self
._ip
= session
['ip']
140 self
._country
= session
['country']
144 self
._lastSessionTime
= 0
150 def _setSavedSession(self
):
152 # Create the directory if it doesn't exist.
153 if not os
.path
.exists(self
.cacheDir
):
154 os
.makedirs(self
.cacheDir
)
155 path
= os
.path
.join(self
.cacheDir
, 'session.dmp')
157 session
= { 'sessionID' : self
._sessionID
, 'lastSessionTime' : self
._lastSessionTime
, 'userID': self
._userID
, 'ip' : self
._ip
, 'country' : self
._country
}
158 pickle
.dump(session
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
161 print "An error occurred during save session"
167 myip
= urllib2
.urlopen('http://ipecho.net/plain').read()
168 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
):
170 print "IP is " + myip
176 def _getCountry(self
):
177 params
= { 'ip' : self
._ip
}
178 response
= self
._callRemote
("getCountry", params
)
179 return response
['result']
181 # Get userid from name
182 def _getUserIDFromUsername(self
, username
):
183 result
= self
._callRemote
('getUserIDFromUsername', {'username' : username
})
184 if 'result' in result
and result
['result']['UserID'] > 0:
185 return result
['result']['UserID']
189 # Authenticates the user for current API session
190 def _authenticate(self
, login
, password
):
191 md5pwd
= md5
.new(password
).hexdigest()
192 params
= {'login': login
, 'password': md5pwd
}
194 result
= self
._callRemote
('authenticate', params
)
196 uid
= result
['result']['UserID']
205 def pingService(self
,):
206 result
= self
._callRemote
('pingService', {});
207 if 'result' in result
and result
['result'] != '':
213 def login(self
, username
, password
):
214 if self
._userID
<= 0:
216 self
._getSavedSession
()
217 if self
._userID
<= 0:
218 self
._userID
= self
._authenticate
(username
, password
)
220 self
._setSavedSession
()
225 result
= self
._callRemote
('logout', {'sessionID' : self
._sessionID
})
226 if 'result' in result
and result
['result']['success'] == True:
228 self
._setSavedSession
()
232 # Gets a stream key and host to get song content
233 def getSubscriberStreamKey(self
, songID
):
234 params
= { "songID": songID
, "country": self
._country
}
235 response
= self
._callRemote
("getSubscriberStreamKey", params
)
237 res
= response
["result"]
243 def getArtistSearchResults(self
, query
, limit
=ARTIST_LIMIT
):
244 result
= self
._callRemote
('getArtistSearchResults', {'query' : query
,'limit' : limit
})
245 if 'result' in result
:
246 return self
._parseArtists
(result
)
251 def getAlbumSearchResults(self
, query
, limit
=ALBUM_LIMIT
):
252 result
= self
._callRemote
('getAlbumSearchResults', {'query' : query
,'limit' : limit
})
253 if 'result' in result
:
254 return self
._parseAlbums
(result
)
259 def getSongSearchResults(self
, query
, limit
=SONG_LIMIT
):
260 result
= self
._callRemote
('getSongSearchResults', {'query' : query
, 'country' : self
._country
, 'limit' : limit
})
261 if 'result' in result
:
262 return self
._parseSongs
(result
)
267 def getArtistAlbums(self
, artistID
, limit
=ALBUM_LIMIT
):
268 result
= self
._callRemote
('getArtistVerifiedAlbums', {'artistID' : artistID
})
269 if 'result' in result
:
270 return self
._parseAlbums
(result
, limit
)
275 def getAlbumSongs(self
, albumID
, limit
=SONG_LIMIT
):
276 result
= self
._callRemote
('getAlbumSongs', {'albumID' : albumID
, 'limit' : limit
})
277 if 'result' in result
:
278 return self
._parseSongs
(result
)
282 # Get artist's popular songs
283 def getArtistPopularSongs(self
, artistID
, limit
= SONG_LIMIT
):
284 result
= self
._callRemote
('getArtistPopularSongs', {'artistID' : artistID
})
285 if 'result' in result
:
286 return self
._parseSongs
(result
, limit
)
290 # Gets the popular songs
291 def getPopularSongsToday(self
, limit
=SONG_LIMIT
):
292 result
= self
._callRemote
('getPopularSongsToday', {'limit' : limit
})
293 if 'result' in result
:
294 # Note limit is broken in the Grooveshark getPopularSongsToday method
295 return self
._parseSongs
(result
, limit
)
299 # Gets the favorite songs of the logged-in user
300 def getUserFavoriteSongs(self
):
301 if (self
._userID
== 0):
303 result
= self
._callRemote
('getUserFavoriteSongs', {})
304 if 'result' in result
:
305 return self
._parseSongs
(result
)
310 def getSongsInfo(self
, songIDs
):
311 result
= self
._callRemote
('getSongsInfo', {'songIDs' : songIDs
})
312 if 'result' in result
and 'SongID' in result
['result']:
313 info
= result
['result']
314 if 'CoverArtFilename' in info
and info
['CoverArtFilename'] != None:
315 info
['CoverArtFilename'] = THUMB_URL
+info
['CoverArtFilename'].encode('ascii', 'ignore')
317 info
['CoverArtFilename'] = 'None'
322 # Add song to user favorites
323 def addUserFavoriteSong(self
, songID
):
324 if (self
._userID
== 0):
326 result
= self
._callRemote
('addUserFavoriteSong', {'songID' : songID
})
327 return result
['result']['success']
329 # Remove songs from user favorites
330 def removeUserFavoriteSongs(self
, songIDs
):
331 if (self
._userID
== 0):
333 result
= self
._callRemote
('removeUserFavoriteSongs', {'songIDs' : songIDs
})
334 return result
['result']['success']
336 # Gets the playlists of the logged-in user
337 def getUserPlaylists(self
):
338 if (self
._userID
== 0):
340 result
= self
._callRemote
('getUserPlaylists', {})
341 if 'result' in result
:
342 return self
._parsePlaylists
(result
)
346 # Gets the playlists of the logged-in user
347 def getUserPlaylistsByUsername(self
, username
):
348 userID
= self
._getUserIDFromUsername
(username
)
350 result
= self
._callRemote
('getUserPlaylistsByUserID', {'userID' : userID
})
351 if 'result' in result
and result
['result']['playlists'] != None:
352 playlists
= result
['result']['playlists']
353 return self
._parsePlaylists
(playlists
)
357 # Creates a playlist with songs
358 def createPlaylist(self
, name
, songIDs
):
359 result
= self
._callRemote
('createPlaylist', {'name' : name
, 'songIDs' : songIDs
})
360 if 'result' in result
and result
['result']['success'] == True:
361 return result
['result']['playlistID']
362 elif 'errors' in result
:
365 # Sets the songs for a playlist
366 def setPlaylistSongs(self
, playlistID
, songIDs
):
367 result
= self
._callRemote
('setPlaylistSongs', {'playlistID' : playlistID
, 'songIDs' : songIDs
})
368 if 'result' in result
and result
['result']['success'] == True:
373 # Gets the songs of a playlist
374 def getPlaylistSongs(self
, playlistID
):
375 result
= self
._callRemote
('getPlaylistSongs', {'playlistID' : playlistID
});
376 if 'result' in result
:
377 return self
._parseSongs
(result
)
382 def playlistDelete(self
, playlistId
):
383 result
= self
._callRemote
("deletePlaylist", {"playlistID": playlistId
})
384 if 'fault' in result
:
389 def playlistRename(self
, playlistId
, name
):
390 result
= self
._callRemote
("renamePlaylist", {"playlistID": playlistId
, "name": name
})
391 if 'fault' in result
:
396 def getSimilarArtists(self
, artistId
, limit
):
397 items
= self
._callRemote
("getSimilarArtists", {"artistID": artistId
, "limit": limit
})
398 if 'result' in items
:
401 artists
= items
['result']['artists']
402 while(i
< len(artists
)):
404 itemList
.append([s
['artistName'].encode('ascii', 'ignore'),\
411 def getDoesArtistExist(self
, artistId
):
412 response
= self
._callRemote
("getDoesArtistExist", {"artistID": artistId
})
413 if 'result' in response
and response
['result'] == True:
418 def getDoesAlbumExist(self
, albumId
):
419 response
= self
._callRemote
("getDoesAlbumExist", {"albumID": albumId
})
420 if 'result' in response
and response
['result'] == True:
425 def getDoesSongExist(self
, songId
):
426 response
= self
._callRemote
("getDoesSongExist", {"songID": songId
})
427 if 'result' in response
and response
['result'] == True:
432 # After 30s play time
433 def markStreamKeyOver30Secs(self
, streamKey
, streamServerID
):
434 params
= { "streamKey" : streamKey
, "streamServerID" : streamServerID
}
435 self
._callRemote
("markStreamKeyOver30Secs", params
)
438 def markSongComplete(self
, songid
, streamKey
, streamServerID
):
439 params
= { "songID" : songid
, "streamKey" : streamKey
, "streamServerID" : streamServerID
}
440 self
._callRemote
("markSongComplete", params
)
443 def _parseSongs(self
, items
, limit
=0):
444 if 'result' in items
:
450 if 'songs' in items
['result'][0]:
451 l
= len(items
['result'][0]['songs'])
455 if l
< 0 and 'songs' in items
['result']:
456 l
= len(items
['result']['songs'])
460 if l
< 0 and 'song' in items
['result']:
466 l
= len(items
['result'])
469 if limit
> 0 and l
> limit
:
472 if index
== 'songs[]':
473 s
= items
['result'][0]['songs'][i
]
474 elif index
== 'songs':
475 s
= items
['result'][index
][i
]
476 elif index
== 'song':
477 s
= items
['result'][index
]
479 s
= items
['result'][i
]
480 if 'CoverArtFilename' not in s
:
481 info
= self
.getSongsInfo(s
['SongID'])
482 coverart
= info
['CoverArtFilename']
483 elif s
['CoverArtFilename'] != None:
484 coverart
= THUMB_URL
+s
['CoverArtFilename'].encode('ascii', 'ignore')
491 itemList
.append([name
.encode('ascii', 'ignore'),\
495 s
['ArtistName'].encode('ascii', 'ignore'),\
503 # Extract artist data
504 def _parseArtists(self
, items
):
505 if 'result' in items
:
508 artists
= items
['result']['artists']
509 while(i
< len(artists
)):
511 itemList
.append([s
['ArtistName'].encode('ascii', 'ignore'),\
519 def _parseAlbums(self
, items
, limit
=0):
520 if 'result' in items
:
524 albums
= items
['result']['albums']
526 res
= items
['result'][0]
527 albums
= res
['albums']
529 if limit
> 0 and l
> limit
:
534 name
= s
['Name'].encode('ascii', 'ignore')
536 name
= s
['AlbumName'].encode('ascii', 'ignore')
537 if 'CoverArtFilename' in s
and s
['CoverArtFilename'] != None:
538 coverart
= THUMB_URL
+s
['CoverArtFilename'].encode('ascii', 'ignore')
541 itemList
.append([s
['ArtistName'].encode('ascii', 'ignore'),\
551 def _parsePlaylists(self
, items
):
554 if 'result' in items
:
555 playlists
= items
['result']['playlists']
561 while (i
< len(playlists
)):
563 itemList
.append([unicode(s
['PlaylistName']).encode('utf8', 'ignore'), s
['PlaylistID']])