b92247fb4fc2c602180b5ac76b7c3749140eaaee
1 import urllib2
, md5
, unicodedata
, re
, os
, traceback
, sys
, pickle
, socket
, xbmc
2 from operator
import itemgetter
, attrgetter
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
):
148 response
= urllib2
.urlopen("http://www.moovida.com/services/grooveshark/session_start")
149 result
= response
.read()
150 result
= self
.simplejson
.loads(result
)
152 if 'fault' in result
:
155 return result
['result']['sessionID']
157 def sessionDestroy(self
):
158 return self
.callRemote("session.destroy")
160 def getSessionFromAPI(self
):
161 result
= self
.callRemote("session.get")
162 if 'fault' in result
:
165 return result
['header']['sessionID']
167 def getStreamURL(self
, songID
):
168 result
= self
.callRemote("song.getStreamUrlEx", {"songID": songID
})
169 if 'result' in result
:
170 return result
['result']['url']
174 def createUserAuthToken(self
, username
, password
):
175 hashpass
= md5
.new(password
).hexdigest()
176 hashpass
= username
+ hashpass
177 hashpass
= md5
.new(hashpass
).hexdigest()
178 result
= self
.callRemote("session.createUserAuthToken", {"username": username
, "hashpass": hashpass
})
179 if 'result' in result
:
180 return result
['result']['token'], result
['result']['userID']
181 elif 'fault' in result
:
182 if result
['fault']['code'] == 256:
183 return -1 # Exceeded the number of allowed tokens. Should not happen
185 return -2 # Unknown error
187 return -2 # Unknown error
189 def destroyUserAuthToken(self
, token
):
190 self
.callRemote("session.destroyAuthToken", {"token": token
})
192 def loginViaAuthToken(self
, token
):
193 result
= self
.callRemote("session.loginViaAuthToken", {"token": token
})
194 self
.destroyUserAuthToken(token
)
195 if 'result' in result
:
196 self
.userID
= result
['result']['userID']
197 return result
['result']['userID']
201 def login(self
, username
, password
):
202 if self
.loggedIn
== 1:
204 result
= self
.createUserAuthToken(username
, password
)
206 raise LoginTokensExceededError()
208 raise LoginUnknownError()
210 self
.token
= result
[0]
211 self
.debug('Token:' + self
.token
)
212 self
.userId
= self
.loginViaAuthToken(self
.token
)
214 raise LoginUnknownError()
220 def loginExt(self
, username
, password
):
221 if self
.loggedIn
== 1:
223 token
= md5
.new(username
.lower() + md5
.new(password
).hexdigest()).hexdigest()
224 result
= self
.callRemote("session.loginExt", {"username": username
, "token": token
})
225 if 'result' in result
:
226 if 'userID' in result
['result']:
228 self
.userId
= result
['result']['userID']
229 return result
['result']['userID']
234 def loginBasic(self
, username
, password
):
235 if self
.loggedIn
== 1:
237 result
= self
.callRemote("session.login", {"username": username
, "password": password
})
238 if 'result' in result
:
239 if 'userID' in result
['result']:
241 self
.userId
= result
['result']['userID']
242 return result
['result']['userID']
246 def loggedInStatus(self
):
250 self
.callRemote("session.logout", {})
253 def getSongInfo(self
, songID
):
254 return self
.callRemote("song.about", {"songID": songID
})['result']['song']
256 def userGetFavoriteSongs(self
, userID
):
257 result
= self
.callRemote("user.getFavoriteSongs", {"userID": userID
})
258 list = self
.parseSongs(result
)
261 def userGetPlaylists(self
, limit
=25):
262 if self
.loggedIn
== 1:
263 result
= self
.callRemote("user.getPlaylists", {"userID": self
.userId
, "limit": limit
})
264 if 'result' in result
:
265 playlists
= result
['result']['playlists']
270 while(i
< len(playlists
)):
272 list.append([p
['playlistName'].encode('ascii', 'ignore'), p
['playlistID']])
274 return sorted(list, key
=itemgetter(0))
278 def playlistCreate(self
, name
, about
):
279 if self
.loggedIn
== 1:
280 result
= self
.callRemote("playlist.create", {"name": name
, "about": about
})
281 if 'result' in result
:
282 return result
['result']['playlistID']
288 def playlistCreateUnique(self
, name
, songIds
):
289 if self
.loggedIn
== 1:
290 result
= self
.callRemote("playlist.createunique", {"name": name
, "songIDs": songIds
})
291 if 'result' in result
:
292 return result
['result']['playlistID']
298 def playlistGetSongs(self
, playlistId
, limit
=25):
299 result
= self
.callRemote("playlist.getSongs", {"playlistID": playlistId
})
300 list = self
.parseSongs(result
)
303 def playlistDelete(self
, playlistId
):
304 if self
.loggedIn
== 1:
305 return self
.callRemote("playlist.delete", {"playlistID": playlistId
})
307 def playlistRename(self
, playlistId
, name
):
308 if self
.loggedIn
== 1:
309 result
= self
.callRemote("playlist.rename", {"playlistID": playlistId
, "name": name
})
310 if 'fault' in result
:
317 def playlistClearSongs(self
, playlistId
):
318 if self
.loggedIn
== 1:
319 return self
.callRemote("playlist.clearSongs", {"playlistID": playlistId
})
321 def playlistAddSong(self
, playlistId
, songId
, position
):
322 if self
.loggedIn
== 1:
323 result
= self
.callRemote("playlist.addSong", {"playlistID": playlistId
, "songID": songId
, "position": position
})
324 if 'fault' in result
:
331 def playlistReplace(self
, playlistId
, songIds
):
332 if self
.loggedIn
== 1:
333 result
= self
.callRemote("playlist.replace", {"playlistID": playlistId
, "songIDs": songIds
})
334 if 'fault' in result
:
341 def radioStartArtists(self
):
342 radio
= self
.getSavedRadio()
345 result
= self
.callRemote("autoplay.startWithArtistIDs", {"artistIDs": radio
['seedArtists']})
346 if 'fault' in result
:
347 print "Cannot autoplay artists"
348 self
.radioEnabled
= False
350 self
.radioEnabled
= True
351 return self
.radioEnabled
353 def radioStartSongs(self
):
354 radio
= self
.getSavedRadio()
357 result
= self
.callRemote("autoplay.start", {"songIDs": radio
['seedSongs']})
358 if 'fault' in result
:
359 print "Cannot autoplay songs"
360 self
.radioEnabled
= False
362 self
.radioEnabled
= True
363 return self
.radioEnabled
365 def radioNextSong(self
):
366 radio
= self
.getSavedRadio()
370 result
= self
.callRemote("autoplay.getNextSongEx", {"seedArtists": radio
['seedArtists'], "frowns": radio
['frowns'], "songIDsAlreadySeen": self
.radioRecentSongs
, "recentArtists": self
.radioRecentArtists
})
371 if 'fault' in result
:
374 song
= self
.parseSongs(result
)
375 self
.radioRecentSongs
.append(song
[0][1])
376 self
.radioRecentArtists
.append(song
[0][7])
379 def radioFrown(self
, songId
= None):
380 radio
= self
.getSavedRadio()
381 if radio
!= None and songId
!= None:
383 radio
['frowns'].remove(songId
)
385 radio
['frowns'].append(songId
)
386 return self
.saveRadio(radio
= radio
)
390 def radioArtist(self
, artistId
= None):
391 radio
= self
.getSavedRadio()
392 if radio
!= None and artistId
!= None:
394 radio
['seedArtists'].remove(artistId
)
396 radio
['seedArtists'].append(artistId
)
398 return self
.saveRadio(radio
= radio
)
400 print "Failed to get radio"
403 def radioSong(self
, songId
= None):
404 radio
= self
.getSavedRadio()
405 if radio
!= None and songId
!= None:
407 radio
['seedSongs'].remove(songId
)
409 radio
['seedSongs'].append(songId
)
411 return self
.saveRadio(radio
= radio
)
413 print "Failed to get radio"
416 def radioTurnedOn(self
):
417 return self
.radioEnabled
419 def getSavedRadio(self
):
420 path
= os
.path
.join(self
.confDir
, 'radio', 'radio.dmp')
423 radio
= pickle
.load(f
)
427 print "Failed to open " + path
429 radio
['seedSongs'] = []
430 radio
['seedArtists'] = []
432 if self
.saveRadio(radio
) == False:
436 def saveRadio(self
, radio
): #blaher
438 print 'Invalid radio'
441 dir = os
.path
.join(self
.confDir
, 'radio')
442 # Create the 'data' directory if it doesn't exist.
443 if not os
.path
.exists(dir):
445 path
= os
.path
.join(dir, 'radio.dmp')
447 pickle
.dump(radio
, f
, protocol
=pickle
.HIGHEST_PROTOCOL
)
451 print 'There was an error while saving the radio pickle (%s)' % e
454 print "An unknown error occurred during save radio: " + str(sys
.exc_info()[0])
457 def favoriteSong(self
, songID
):
458 return self
.callRemote("song.favorite", {"songID": songID
})
460 def unfavoriteSong(self
, songID
):
461 return self
.callRemote("song.unfavorite", {"songID": songID
})
463 def getMethods(self
):
464 return self
.callRemote("service.getMethods")
466 def searchSongsExactMatch(self
, songName
, artistName
, albumName
):
467 result
= self
.callRemote("search.songExactMatch", {"songName": songName
, "artistName": artistName
, "albumName": albumName
})
468 list = self
.parseSongs(result
)
471 def searchSongs(self
, query
, limit
, page
=0, sortKey
=6):
472 result
= self
.callRemote("search.songs", {"query": query
, "limit": limit
, "page:": page
, "streamableOnly": 1})
473 list = self
.parseSongs(result
)
475 #return sorted(list, key=itemgetter(sortKey))
477 def searchArtists(self
, query
, limit
, sortKey
=0):
478 result
= self
.callRemote("search.artists", {"query": query
, "limit": limit
, "streamableOnly": 1})
479 list = self
.parseArtists(result
)
481 #return sorted(list, key=itemgetter(sortKey))
483 def searchAlbums(self
, query
, limit
, sortKey
=2):
484 result
= self
.callRemote("search.albums", {"query": query
, "limit": limit
, "streamableOnly": 1})
485 list = self
.parseAlbums(result
)
487 #return sorted(list, key=itemgetter(sortKey))
489 def searchPlaylists(self
, query
, limit
):
490 result
= self
.callRemote("search.playlists", {"query": query
, "limit": limit
, "streamableOnly": 1})
491 list = self
.parsePlaylists(result
)
494 def popularGetSongs(self
, limit
):
495 result
= self
.callRemote("popular.getSongs", {"limit": limit
})
496 list = self
.parseSongs(result
)
499 def popularGetArtists(self
, limit
):
500 result
= self
.callRemote("popular.getArtists", {"limit": limit
})
501 list = self
.parseArtists(result
)
504 def popularGetAlbums(self
, limit
):
505 result
= self
.callRemote("popular.getAlbums", {"limit": limit
})
506 list = self
.parseAlbums(result
)
509 def artistAbout(self
, artistId
):
510 result
= self
.callRemote("artist.about", {"artistID": artistId
})
513 def artistGetAlbums(self
, artistId
, limit
, sortKey
=2):
514 result
= self
.callRemote("artist.getAlbums", {"artistID": artistId
, "limit": limit
})
515 list = self
.parseAlbums(result
)
517 #return sorted(list, key=itemgetter(sortKey))
519 def artistGetVerifiedAlbums(self
, artistId
, limit
):
520 result
= self
.callRemote("artist.getVerifiedAlbums", {"artistID": artistId
, "limit": limit
})
521 list = self
.parseSongs(result
)
524 def albumGetSongs(self
, albumId
, limit
):
525 result
= self
.callRemote("album.getSongs", {"albumID": albumId
, "limit": limit
})
526 list = self
.parseSongs(result
)
529 def songGetSimilar(self
, songId
, limit
):
530 result
= self
.callRemote("song.getSimilar", {"songID": songId
, "limit": limit
})
531 list = self
.parseSongs(result
)
534 def artistGetSimilar(self
, artistId
, limit
):
535 result
= self
.callRemote("artist.getSimilar", {"artistID": artistId
, "limit": limit
})
536 list = self
.parseArtists(result
)
539 def songAbout(self
, songId
):
540 result
= self
.callRemote("song.about", {"songID": songId
})
541 return result
['result']['song']
543 def getVersion(self
):
544 result
= self
.callRemote("service.getVersion", {})
547 def parseSongs(self
, items
):
549 if 'result' in items
:
552 if 'songs' in items
['result']:
553 l
= len(items
['result']['songs'])
555 elif 'song' in items
['result']:
563 s
= items
['result'][index
][i
]
565 s
= items
['result'][index
]
566 if 'estDurationSecs' in s
:
567 dur
= s
['estDurationSecs']
573 songName
= s
['songName'].encode('ascii', 'ignore')
574 albumName
= s
['albumName'].encode('ascii', 'ignore')
575 artistName
= s
['artistName'].encode('ascii', 'ignore')
576 if self
.removeDuplicates
== True:
577 if (entry
[0].lower() == songName
.lower()) and (entry
[3].lower() == albumName
.lower()) and (entry
[6].lower() == artistName
.lower()):
580 list.append([s
['songName'].encode('ascii', 'ignore'),\
583 s
['albumName'].encode('ascii', 'ignore'),\
585 s
['image']['tiny'].encode('ascii', 'ignore'),\
586 s
['artistName'].encode('ascii', 'ignore'),\
588 s
['image']['small'].encode('ascii', 'ignore'),\
589 s
['image']['medium'].encode('ascii', 'ignore')])
591 print 'GrooveShark: Could not parse song number: ' + str(i
)
592 traceback
.print_exc()
599 print 'GrooveShark: Could not parse songs. Got this:'
600 traceback
.print_exc()
603 def parseArtists(self
, items
):
605 if 'result' in items
:
608 artists
= items
['result']['artists']
609 while(i
< len(artists
)):
612 list.append([s
['artistName'].encode('ascii', 'ignore'),\
615 print 'GrooveShark: Could not parse album number: ' + str(i
)
616 traceback
.print_exc()
622 print 'GrooveShark: Could not parse artists. Got this:'
623 traceback
.print_exc()
626 def parseAlbums(self
, items
):
628 if 'result' in items
:
631 albums
= items
['result']['albums']
632 while(i
< len(albums
)):
634 try: # Avoid ascii ancoding errors
635 list.append([s
['artistName'].encode('ascii', 'ignore'),\
637 s
['albumName'].encode('ascii', 'ignore'),\
639 s
['image']['medium'].encode('ascii', 'ignore')])
641 print 'GrooveShark: Could not parse album number: ' + str(i
)
642 traceback
.print_exc()
648 print 'GrooveShark: Could not parse albums. Got this'
649 traceback
.print_exc()
652 def parsePlaylists(self
, items
):
654 if 'result' in items
:
657 playlists
= items
['result']['playlists']
658 while(i
< len(playlists
)):
660 try: # Avoid ascii ancoding errors
661 list.append([s
['playlistID'],\
662 s
['playlistName'].encode('ascii', 'ignore'),\
663 s
['username'].encode('ascii', 'ignore')])
665 print 'GrooveShark: Could not parse playlist number: ' + str(i
)
666 traceback
.print_exc()
672 print 'GrooveShark: Could not parse playlists. Got this:'