1 import urllib2
, md5
, os
, traceback
, sys
, pickle
, socket
, xbmc
2 from operator
import itemgetter
4 class LoginTokensExceededError(Exception):
6 self
.value
= 'You have created to many tokens. Only 12 are allowed'
8 return repr(self
.value
)
10 class LoginUnknownError(Exception):
12 self
.value
= 'Unable to get a new session ID. Wait a few minutes and try again'
14 return repr(self
.value
)
16 class SessionIDTryAgainError(Exception):
18 self
.value
= 'Unable to get a new session ID. Wait a few minutes and try again'
20 return repr(self
.value
)
23 def __init__(self
, enableDebug
= False, isXbox
= False):
25 self
.simplejson
= simplejson
27 socket
.setdefaulttimeout(timeout
)
28 self
.enableDebug
= enableDebug
31 self
.removeDuplicates
= False
33 self
.radioRecentSongs
= []
34 self
.radioRecentArtists
= []
35 self
.radioEnabled
= False
37 self
.dataDir
= 'addon_data'
38 self
.confDir
= xbmc
.translatePath(os
.path
.join('special://masterprofile/' + self
.dataDir
, os
.path
.basename(os
.getcwd())))
39 self
.sessionID
= self
.getSavedSession()
40 self
.debug('Saved sessionID: ' + self
.sessionID
)
41 #self.sessionID = self.getSessionFromAPI()
42 #self.debug('API sessionID: ' + self.sessionID)
43 if self
.sessionID
== '':
44 self
.sessionID
= self
.startSession()
45 self
.debug('Start() sessionID: ' + self
.sessionID
)
46 if self
.sessionID
== '':
47 self
.debug('Could not get a sessionID. Try again in a few minutes')
48 raise SessionIDTryAgainError()
52 self
.debug('sessionID: ' + self
.sessionID
)
56 if self
.loggedIn
== 1:
62 if self
.enableDebug
== True:
65 def setRemoveDuplicates(self
, enable
):
66 if enable
== True or enable
== 'true' or enable
== 'True':
67 self
.removeDuplicates
= True
69 self
.removeDuplicates
= False
71 def getSavedSession(self
):
73 path
= os
.path
.join(self
.confDir
, 'session', 'session.txt')
77 sessionID
= pickle
.load(f
)
85 def saveSession(self
):
87 dir = os
.path
.join(self
.confDir
, 'session')
88 # Create the 'data' directory if it doesn't exist.
89 if not os
.path
.exists(dir):
91 path
= os
.path
.join(dir, 'session.txt')
93 pickle
.dump(self
.sessionID
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
96 print 'There was an error while saving the session pickle (%s)' % e
99 print "An unknown error occured during save session: " + str(sys
.exc_info()[0])
102 def saveSettings(self
):
104 dir = os
.path
.join(self
.confDir
, 'data')
105 # Create the 'data' directory if it doesn't exist.
106 if not os
.path
.exists(dir):
108 path
= os
.path
.join(dir, 'settings1.txt')
110 pickle
.dump(self
.settings
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
113 print 'There was an error while saving the settings pickle (%s)' % e
116 print "An unknown error occured during save settings\n"
119 def callRemote(self
, method
, params
={}):
120 data
= {'header': {'sessionID': self
.sessionID
}, 'method': method
, 'parameters': params
}
121 data
= self
.simplejson
.dumps(data
)
122 req
= urllib2
.Request("http://api.grooveshark.com/ws/1.0/?json")
123 req
.add_header('Host', 'api.grooveshark.com')
124 req
.add_header('Content-type', 'text/json')
125 req
.add_header('Content-length', str(len(data
)))
127 response
= urllib2
.urlopen(req
)
128 result
= response
.read()
131 result
= self
.simplejson
.loads(result
)
132 if 'fault' in result
:
134 if result
['fault']['code'] == 8: #Session ID has expired. Get a new and try again if possible.
135 self
.debug(result
['fault']['message'])
136 self
.sessionID
= self
.startSession()
137 if self
.sessionID
!= '':
139 return self
.callRemote(method
, params
)
141 self
.debug('GrooveShark: SessionID expired, but unable to get new')
147 def startSession(self
):
149 response
= urllib2
.urlopen("http://www.moovida.com/services/grooveshark/session_start")
150 result
= response
.read()
151 result
= self
.simplejson
.loads(result
)
156 if 'fault' in result
:
159 return result
['result']['sessionID']
161 def sessionDestroy(self
):
162 return self
.callRemote("session.destroy")
164 def getSessionFromAPI(self
):
165 result
= self
.callRemote("session.get")
166 if 'fault' in result
:
169 return result
['header']['sessionID']
171 def getStreamURL(self
, songID
):
172 result
= self
.callRemote("song.getStreamUrlEx", {"songID": songID
})
173 if 'result' in result
:
174 return result
['result']['url']
178 def createUserAuthToken(self
, username
, password
):
179 hashpass
= md5
.new(password
).hexdigest()
180 hashpass
= username
+ hashpass
181 hashpass
= md5
.new(hashpass
).hexdigest()
182 result
= self
.callRemote("session.createUserAuthToken", {"username": username
, "hashpass": hashpass
})
183 if 'result' in result
:
184 return result
['result']['token'], result
['result']['userID']
185 elif 'fault' in result
:
186 if result
['fault']['code'] == 256:
187 return -1 # Exceeded the number of allowed tokens. Should not happen
189 return -2 # Unknown error
191 return -2 # Unknown error
193 def destroyUserAuthToken(self
, token
):
194 self
.callRemote("session.destroyAuthToken", {"token": token
})
196 def loginViaAuthToken(self
, token
):
197 result
= self
.callRemote("session.loginViaAuthToken", {"token": token
})
198 self
.destroyUserAuthToken(token
)
199 if 'result' in result
:
200 self
.userID
= result
['result']['userID']
201 return result
['result']['userID']
205 def login(self
, username
, password
):
206 if self
.loggedIn
== 1:
208 result
= self
.createUserAuthToken(username
, password
)
210 raise LoginTokensExceededError()
212 raise LoginUnknownError()
214 self
.token
= result
[0]
215 self
.debug('Token:' + self
.token
)
216 self
.userId
= self
.loginViaAuthToken(self
.token
)
218 raise LoginUnknownError()
224 def loginExt(self
, username
, password
):
225 if self
.loggedIn
== 1:
227 token
= md5
.new(username
.lower() + md5
.new(password
).hexdigest()).hexdigest()
228 result
= self
.callRemote("session.loginExt", {"username": username
, "token": token
})
229 if 'result' in result
:
230 if 'userID' in result
['result']:
232 self
.userId
= result
['result']['userID']
233 return result
['result']['userID']
238 def loginBasic(self
, username
, password
):
239 if self
.loggedIn
== 1:
241 result
= self
.callRemote("session.login", {"username": username
, "password": password
})
242 if 'result' in result
:
243 if 'userID' in result
['result']:
245 self
.userId
= result
['result']['userID']
246 return result
['result']['userID']
250 def loggedInStatus(self
):
254 self
.callRemote("session.logout", {})
257 def getSongInfo(self
, songID
):
258 return self
.callRemote("song.about", {"songID": songID
})['result']['song']
260 def userGetFavoriteSongs(self
, userID
):
261 result
= self
.callRemote("user.getFavoriteSongs", {"userID": userID
})
262 list = self
.parseSongs(result
)
265 def userGetPlaylists(self
, limit
=25):
266 if self
.loggedIn
== 1:
267 result
= self
.callRemote("user.getPlaylists", {"userID": self
.userId
, "limit": limit
})
268 if 'result' in result
:
269 playlists
= result
['result']['playlists']
274 while(i
< len(playlists
)):
276 list.append([p
['playlistName'].encode('ascii', 'ignore'), p
['playlistID']])
278 return sorted(list, key
=itemgetter(0))
282 def playlistCreate(self
, name
, about
):
283 if self
.loggedIn
== 1:
284 result
= self
.callRemote("playlist.create", {"name": name
, "about": about
})
285 if 'result' in result
:
286 return result
['result']['playlistID']
292 def playlistCreateUnique(self
, name
, songIds
):
293 if self
.loggedIn
== 1:
294 result
= self
.callRemote("playlist.createunique", {"name": name
, "songIDs": songIds
})
295 if 'result' in result
:
296 return result
['result']['playlistID']
302 def playlistGetSongs(self
, playlistId
, limit
=25):
303 result
= self
.callRemote("playlist.getSongs", {"playlistID": playlistId
})
304 list = self
.parseSongs(result
)
307 def playlistDelete(self
, playlistId
):
308 if self
.loggedIn
== 1:
309 result
= self
.callRemote("playlist.delete", {"playlistID": playlistId
})
310 if 'fault' in result
:
317 def playlistRename(self
, playlistId
, name
):
318 if self
.loggedIn
== 1:
319 result
= self
.callRemote("playlist.rename", {"playlistID": playlistId
, "name": name
})
320 if 'fault' in result
:
327 def playlistClearSongs(self
, playlistId
):
328 if self
.loggedIn
== 1:
329 return self
.callRemote("playlist.clearSongs", {"playlistID": playlistId
})
331 def playlistAddSong(self
, playlistId
, songId
, position
):
332 if self
.loggedIn
== 1:
333 result
= self
.callRemote("playlist.addSong", {"playlistID": playlistId
, "songID": songId
, "position": position
})
334 if 'fault' in result
:
341 def playlistDeleteSong(self
, playlistId
, position
):
342 if self
.loggedIn
== 1:
343 result
= self
.callRemote("playlist.removeSong", {"playlistID": playlistId
, "position": position
})
344 if 'fault' in result
:
351 def playlistReplace(self
, playlistId
, songIds
):
352 if self
.loggedIn
== 1:
353 result
= self
.callRemote("playlist.replace", {"playlistID": playlistId
, "songIDs": songIds
})
354 if 'fault' in result
:
361 def radioStartArtists(self
):
362 radio
= self
.getSavedRadio()
365 result
= self
.callRemote("autoplay.startWithArtistIDs", {"artistIDs": radio
['seedArtists']})
366 if 'fault' in result
:
367 print "Cannot autoplay artists"
368 self
.radioEnabled
= False
370 self
.radioEnabled
= True
371 return self
.radioEnabled
373 def radioStartSongs(self
):
374 radio
= self
.getSavedRadio()
377 result
= self
.callRemote("autoplay.start", {"songIDs": radio
['seedSongs']})
378 if 'fault' in result
:
379 print "Cannot autoplay songs"
380 self
.radioEnabled
= False
382 self
.radioEnabled
= True
383 return self
.radioEnabled
385 def radioNextSong(self
):
386 radio
= self
.getSavedRadio()
390 result
= self
.callRemote("autoplay.getNextSongEx", {"seedArtists": radio
['seedArtists'], "frowns": radio
['frowns'], "songIDsAlreadySeen": self
.radioRecentSongs
, "recentArtists": self
.radioRecentArtists
})
391 if 'fault' in result
:
394 song
= self
.parseSongs(result
)
395 self
.radioRecentSongs
.append(song
[0][1])
396 self
.radioRecentArtists
.append(song
[0][7])
399 def radioFrown(self
, songId
= None):
400 radio
= self
.getSavedRadio()
401 if radio
!= None and songId
!= None:
403 radio
['frowns'].remove(songId
)
405 radio
['frowns'].append(songId
)
406 return self
.saveRadio(radio
= radio
)
410 def radioArtist(self
, artistId
= None):
411 radio
= self
.getSavedRadio()
412 if radio
!= None and artistId
!= None:
414 radio
['seedArtists'].remove(artistId
)
416 radio
['seedArtists'].append(artistId
)
418 return self
.saveRadio(radio
= radio
)
420 print "Failed to get radio"
423 def radioSong(self
, songId
= None):
424 radio
= self
.getSavedRadio()
425 if radio
!= None and songId
!= None:
427 radio
['seedSongs'].remove(songId
)
429 radio
['seedSongs'].append(songId
)
431 return self
.saveRadio(radio
= radio
)
433 print "Failed to get radio"
436 def radioTurnedOn(self
):
437 return self
.radioEnabled
439 def getSavedRadio(self
):
440 path
= os
.path
.join(self
.confDir
, 'radio', 'radio.dmp')
443 radio
= pickle
.load(f
)
446 print "Failed to open " + path
448 radio
['seedSongs'] = []
449 radio
['seedArtists'] = []
451 if self
.saveRadio(radio
) == False:
455 def saveRadio(self
, radio
): #blaher
457 print 'Invalid radio'
460 dir = os
.path
.join(self
.confDir
, 'radio')
461 # Create the 'data' directory if it doesn't exist.
462 if not os
.path
.exists(dir):
464 path
= os
.path
.join(dir, 'radio.dmp')
466 pickle
.dump(radio
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
470 print 'There was an error while saving the radio pickle (%s)' % e
473 print "An unknown error occurred during save radio: " + str(sys
.exc_info()[0])
476 def favoriteSong(self
, songID
):
477 return self
.callRemote("song.favorite", {"songID": songID
})
479 def unfavoriteSong(self
, songID
):
480 return self
.callRemote("song.unfavorite", {"songID": songID
})
482 def getMethods(self
):
483 return self
.callRemote("service.getMethods")
485 def searchSongsExactMatch(self
, songName
, artistName
, albumName
):
486 result
= self
.callRemote("search.songExactMatch", {"songName": songName
, "artistName": artistName
, "albumName": albumName
})
487 list = self
.parseSongs(result
)
490 def searchSongs(self
, query
, limit
, page
=0, sortKey
=6):
491 result
= self
.callRemote("search.songs", {"query": query
, "limit": limit
, "page:": page
, "streamableOnly": 1})
492 list = self
.parseSongs(result
)
494 #return sorted(list, key=itemgetter(sortKey))
496 def searchArtists(self
, query
, limit
, sortKey
=0):
497 result
= self
.callRemote("search.artists", {"query": query
, "limit": limit
, "streamableOnly": 1})
498 list = self
.parseArtists(result
)
500 #return sorted(list, key=itemgetter(sortKey))
502 def searchAlbums(self
, query
, limit
, sortKey
=2):
503 result
= self
.callRemote("search.albums", {"query": query
, "limit": limit
, "streamableOnly": 1})
504 list = self
.parseAlbums(result
)
506 #return sorted(list, key=itemgetter(sortKey))
508 def searchPlaylists(self
, query
, limit
):
509 result
= self
.callRemote("search.playlists", {"query": query
, "limit": limit
, "streamableOnly": 1})
510 list = self
.parsePlaylists(result
)
513 def popularGetSongs(self
, limit
):
514 result
= self
.callRemote("popular.getSongs", {"limit": limit
})
515 list = self
.parseSongs(result
)
518 def popularGetArtists(self
, limit
):
519 result
= self
.callRemote("popular.getArtists", {"limit": limit
})
520 list = self
.parseArtists(result
)
523 def popularGetAlbums(self
, limit
):
524 result
= self
.callRemote("popular.getAlbums", {"limit": limit
})
525 list = self
.parseAlbums(result
)
528 def artistAbout(self
, artistId
):
529 result
= self
.callRemote("artist.about", {"artistID": artistId
})
532 def artistGetAlbums(self
, artistId
, limit
, sortKey
=2):
533 result
= self
.callRemote("artist.getAlbums", {"artistID": artistId
, "limit": limit
})
534 list = self
.parseAlbums(result
)
536 #return sorted(list, key=itemgetter(sortKey))
538 def artistGetVerifiedAlbums(self
, artistId
, limit
):
539 result
= self
.callRemote("artist.getVerifiedAlbums", {"artistID": artistId
, "limit": limit
})
540 list = self
.parseSongs(result
)
543 def albumGetSongs(self
, albumId
, limit
):
544 result
= self
.callRemote("album.getSongs", {"albumID": albumId
, "limit": limit
})
545 list = self
.parseSongs(result
)
548 def songGetSimilar(self
, songId
, limit
):
549 result
= self
.callRemote("song.getSimilar", {"songID": songId
, "limit": limit
})
550 list = self
.parseSongs(result
)
553 def artistGetSimilar(self
, artistId
, limit
):
554 result
= self
.callRemote("artist.getSimilar", {"artistID": artistId
, "limit": limit
})
555 list = self
.parseArtists(result
)
558 def songAbout(self
, songId
):
559 result
= self
.callRemote("song.about", {"songID": songId
})
560 return result
['result']['song']
562 def getVersion(self
):
563 result
= self
.callRemote("service.getVersion", {})
566 def parseSongs(self
, items
):
568 if 'result' in items
:
571 if 'songs' in items
['result']:
572 l
= len(items
['result']['songs'])
574 elif 'song' in items
['result']:
582 s
= items
['result'][index
][i
]
584 s
= items
['result'][index
]
585 if 'estDurationSecs' in s
:
586 dur
= s
['estDurationSecs']
592 songName
= s
['songName'].encode('ascii', 'ignore')
593 albumName
= s
['albumName'].encode('ascii', 'ignore')
594 artistName
= s
['artistName'].encode('ascii', 'ignore')
595 if self
.removeDuplicates
== True:
596 if (entry
[0].lower() == songName
.lower()) and (entry
[3].lower() == albumName
.lower()) and (entry
[6].lower() == artistName
.lower()):
599 list.append([s
['songName'].encode('ascii', 'ignore'),\
602 s
['albumName'].encode('ascii', 'ignore'),\
604 s
['image']['tiny'].encode('ascii', 'ignore'),\
605 s
['artistName'].encode('ascii', 'ignore'),\
607 s
['image']['small'].encode('ascii', 'ignore'),\
608 s
['image']['medium'].encode('ascii', 'ignore')])
610 print 'GrooveShark: Could not parse song number: ' + str(i
)
611 traceback
.print_exc()
618 print 'GrooveShark: Could not parse songs. Got this:'
619 traceback
.print_exc()
622 def parseArtists(self
, items
):
624 if 'result' in items
:
627 artists
= items
['result']['artists']
628 while(i
< len(artists
)):
631 list.append([s
['artistName'].encode('ascii', 'ignore'),\
634 print 'GrooveShark: Could not parse album number: ' + str(i
)
635 traceback
.print_exc()
641 print 'GrooveShark: Could not parse artists. Got this:'
642 traceback
.print_exc()
645 def parseAlbums(self
, items
):
647 if 'result' in items
:
650 albums
= items
['result']['albums']
651 while(i
< len(albums
)):
653 try: # Avoid ascii ancoding errors
654 list.append([s
['artistName'].encode('ascii', 'ignore'),\
656 s
['albumName'].encode('ascii', 'ignore'),\
658 s
['image']['medium'].encode('ascii', 'ignore')])
660 print 'GrooveShark: Could not parse album number: ' + str(i
)
661 traceback
.print_exc()
667 print 'GrooveShark: Could not parse albums. Got this'
668 traceback
.print_exc()
671 def parsePlaylists(self
, items
):
673 if 'result' in items
:
676 playlists
= items
['result']['playlists']
677 while(i
< len(playlists
)):
679 try: # Avoid ascii ancoding errors
680 list.append([s
['playlistID'],\
681 s
['playlistName'].encode('ascii', 'ignore'),\
682 s
['username'].encode('ascii', 'ignore')])
684 print 'GrooveShark: Could not parse playlist number: ' + str(i
)
685 traceback
.print_exc()
691 print 'GrooveShark: Could not parse playlists. Got this:'