Add Grooveshark playlist support.
[clinton/xbmc-groove.git] / resources / lib / GrooveAPI.py
CommitLineData
b738088f 1import urllib2, md5, unicodedata, re, os, traceback, sys, pickle, socket, xbmc
8817bb2e 2from operator import itemgetter, attrgetter
3
4class LoginTokensExceededError(Exception):
5 def __init__(self):
6 self.value = 'You have created to many tokens. Only 12 are allowed'
7 def __str__(self):
8 return repr(self.value)
9
10class LoginUnknownError(Exception):
11 def __init__(self):
12 self.value = 'Unable to get a new session ID. Wait a few minutes and try again'
13 def __str__(self):
14 return repr(self.value)
15
16class SessionIDTryAgainError(Exception):
17 def __init__(self):
18 self.value = 'Unable to get a new session ID. Wait a few minutes and try again'
19 def __str__(self):
20 return repr(self.value)
21
22class GrooveAPI:
23 def __init__(self, enableDebug = False, isXbox = False):
b738088f 24 import simplejson
25 self.simplejson = simplejson
8817bb2e 26 timeout = 40
27 socket.setdefaulttimeout(timeout)
28 self.enableDebug = enableDebug
29 self.loggedIn = 0
8817bb2e 30 self.userId = 0
b738088f 31 self.removeDuplicates = False
3fcef5ba 32
33 self.radioRecentSongs = []
34 self.radioRecentArtists = []
35 self.radioEnabled = False
36
973b4c6c 37 self.dataDir = 'addon_data'
b738088f 38 self.confDir = xbmc.translatePath(os.path.join('special://masterprofile/' + self.dataDir, os.path.basename(os.getcwd())))
8817bb2e 39 self.sessionID = self.getSavedSession()
40 self.debug('Saved sessionID: ' + self.sessionID)
b738088f 41 #self.sessionID = self.getSessionFromAPI()
42 #self.debug('API sessionID: ' + self.sessionID)
8817bb2e 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()
49 else:
50 self.saveSession()
51
52 self.debug('sessionID: ' + self.sessionID)
53
54 def __del__(self):
55 try:
56 if self.loggedIn == 1:
57 self.logout()
58 except:
59 pass
60
61 def debug(self, msg):
62 if self.enableDebug == True:
63 print msg
b738088f 64
65 def setRemoveDuplicates(self, enable):
66 if enable == True or enable == 'true' or enable == 'True':
67 self.removeDuplicates = True
68 else:
69 self.removeDuplicates = False
8817bb2e 70
71 def getSavedSession(self):
72 sessionID = ''
b738088f 73 path = os.path.join(self.confDir, 'session', 'session.txt')
8817bb2e 74
75 try:
76 f = open(path, 'rb')
77 sessionID = pickle.load(f)
78 f.close()
79 except:
80 sessionID = ''
81 pass
82
83 return sessionID
84
85 def saveSession(self):
86 try:
b738088f 87 dir = os.path.join(self.confDir, 'session')
8817bb2e 88 # Create the 'data' directory if it doesn't exist.
89 if not os.path.exists(dir):
b738088f 90 os.makedirs(dir)
8817bb2e 91 path = os.path.join(dir, 'session.txt')
92 f = open(path, 'wb')
93 pickle.dump(self.sessionID, f, protocol=pickle.HIGHEST_PROTOCOL)
94 f.close()
95 except IOError, e:
96 print 'There was an error while saving the session pickle (%s)' % e
97 pass
98 except:
99 print "An unknown error occured during save session: " + str(sys.exc_info()[0])
100 pass
101
102 def saveSettings(self):
103 try:
b738088f 104 dir = os.path.join(self.confDir, 'data')
8817bb2e 105 # Create the 'data' directory if it doesn't exist.
106 if not os.path.exists(dir):
b738088f 107 os.makedirs(dir)
8817bb2e 108 path = os.path.join(dir, 'settings1.txt')
109 f = open(path, 'wb')
110 pickle.dump(self.settings, f, protocol=pickle.HIGHEST_PROTOCOL)
111 f.close()
112 except IOError, e:
113 print 'There was an error while saving the settings pickle (%s)' % e
114 pass
115 except:
116 print "An unknown error occured during save settings\n"
117 pass
118
119 def callRemote(self, method, params={}):
120 data = {'header': {'sessionID': self.sessionID}, 'method': method, 'parameters': params}
8817bb2e 121 data = self.simplejson.dumps(data)
8817bb2e 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)))
126 req.add_data(data)
127 response = urllib2.urlopen(req)
128 result = response.read()
129 response.close()
130 try:
131 result = self.simplejson.loads(result)
132 if 'fault' in result:
133 self.debug(result)
b738088f 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 != '':
138 self.saveSession()
139 return self.callRemote(method, params)
140 else:
141 self.debug('GrooveShark: SessionID expired, but unable to get new')
142 return []
8817bb2e 143 return result
144 except:
145 return []
146
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)
151 response.close()
152 if 'fault' in result:
153 return ''
154 else:
3fcef5ba 155 return result['result']['sessionID']
8817bb2e 156
157 def sessionDestroy(self):
158 return self.callRemote("session.destroy")
159
160 def getSessionFromAPI(self):
161 result = self.callRemote("session.get")
162 if 'fault' in result:
163 return ''
164 else:
165 return result['header']['sessionID']
166
167 def getStreamURL(self, songID):
168 result = self.callRemote("song.getStreamUrlEx", {"songID": songID})
169 if 'result' in result:
170 return result['result']['url']
171 else:
172 return ''
173
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
184 else:
185 return -2 # Unknown error
186 else:
187 return -2 # Unknown error
188
189 def destroyUserAuthToken(self, token):
190 self.callRemote("session.destroyAuthToken", {"token": token})
191
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']
198 else:
199 return 0
200
201 def login(self, username, password):
202 if self.loggedIn == 1:
203 return self.userId
204 result = self.createUserAuthToken(username, password)
205 if result == -1:
206 raise LoginTokensExceededError()
207 elif result == -2:
208 raise LoginUnknownError()
209 else:
210 self.token = result[0]
211 self.debug('Token:' + self.token)
212 self.userId = self.loginViaAuthToken(self.token)
213 if self.userId == 0:
214 raise LoginUnknownError()
215 else:
216 self.loggedIn = 1
217 return self.userId
b738088f 218
8817bb2e 219
220 def loginExt(self, username, password):
221 if self.loggedIn == 1:
222 return self.userId
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']:
227 self.loggedIn = 1
228 self.userId = result['result']['userID']
229 return result['result']['userID']
230 else:
231 return 0
232
233
234 def loginBasic(self, username, password):
235 if self.loggedIn == 1:
236 return self.userId
237 result = self.callRemote("session.login", {"username": username, "password": password})
238 if 'result' in result:
239 if 'userID' in result['result']:
240 self.loggedIn = 1
241 self.userId = result['result']['userID']
242 return result['result']['userID']
243 else:
244 return 0
245
246 def loggedInStatus(self):
247 return self.loggedIn
248
249 def logout(self):
250 self.callRemote("session.logout", {})
251 self.loggedIn = 0
252
253 def getSongInfo(self, songID):
254 return self.callRemote("song.about", {"songID": songID})['result']['song']
255
256 def userGetFavoriteSongs(self, userID):
257 result = self.callRemote("user.getFavoriteSongs", {"userID": userID})
258 list = self.parseSongs(result)
259 return list
260
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']
266 else:
267 return []
268 i = 0
269 list = []
270 while(i < len(playlists)):
271 p = playlists[i]
272 list.append([p['playlistName'].encode('ascii', 'ignore'), p['playlistID']])
273 i = i + 1
274 return sorted(list, key=itemgetter(0))
275 else:
276 return []
277
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']
283 else:
284 return 0
285 else:
286 return 0
36cc00d7 287
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']
293 else:
294 return 0
295 else:
296 return 0
8817bb2e 297
298 def playlistGetSongs(self, playlistId, limit=25):
299 result = self.callRemote("playlist.getSongs", {"playlistID": playlistId})
300 list = self.parseSongs(result)
301 return list
302
303 def playlistDelete(self, playlistId):
304 if self.loggedIn == 1:
305 return self.callRemote("playlist.delete", {"playlistID": playlistId})
306
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:
311 return 0
312 else:
313 return 1
314 else:
315 return 0
316
317 def playlistClearSongs(self, playlistId):
318 if self.loggedIn == 1:
319 return self.callRemote("playlist.clearSongs", {"playlistID": playlistId})
320
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:
325 return 0
326 else:
327 return 1
328 else:
329 return 0
330
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:
335 return 0
336 else:
337 return 1
338 else:
339 return 0
340
3fcef5ba 341 def radioStartArtists(self):
342 radio = self.getSavedRadio()
343 if radio == None:
344 return False
345 result = self.callRemote("autoplay.startWithArtistIDs", {"artistIDs": radio['seedArtists']})
8817bb2e 346 if 'fault' in result:
e6ccfeca 347 print "Cannot autoplay artists"
3fcef5ba 348 self.radioEnabled = False
8817bb2e 349 else:
3fcef5ba 350 self.radioEnabled = True
351 return self.radioEnabled
8817bb2e 352
3fcef5ba 353 def radioStartSongs(self):
354 radio = self.getSavedRadio()
355 if radio == None:
356 return False
357 result = self.callRemote("autoplay.start", {"songIDs": radio['seedSongs']})
8817bb2e 358 if 'fault' in result:
e6ccfeca 359 print "Cannot autoplay songs"
3fcef5ba 360 self.radioEnabled = False
8817bb2e 361 else:
3fcef5ba 362 self.radioEnabled = True
363 return self.radioEnabled
8817bb2e 364
3fcef5ba 365 def radioNextSong(self):
b738088f 366 radio = self.getSavedRadio()
367 if radio == None:
368 return None
8817bb2e 369 else:
3fcef5ba 370 result = self.callRemote("autoplay.getNextSongEx", {"seedArtists": radio['seedArtists'], "frowns": radio['frowns'], "songIDsAlreadySeen": self.radioRecentSongs, "recentArtists": self.radioRecentArtists})
8817bb2e 371 if 'fault' in result:
372 return []
373 else:
374 song = self.parseSongs(result)
3fcef5ba 375 self.radioRecentSongs.append(song[0][1])
376 self.radioRecentArtists.append(song[0][7])
8817bb2e 377 return song
378
3fcef5ba 379 def radioFrown(self, songId = None):
380 radio = self.getSavedRadio()
381 if radio != None and songId != None:
382 try:
383 radio['frowns'].remove(songId)
384 except: pass
385 radio['frowns'].append(songId)
b738088f 386 return self.saveRadio(radio = radio)
387 else:
3fcef5ba 388 return False
8817bb2e 389
3fcef5ba 390 def radioArtist(self, artistId = None):
391 radio = self.getSavedRadio()
392 if radio != None and artistId != None:
393 try:
394 radio['seedArtists'].remove(artistId)
395 except: pass
396 radio['seedArtists'].append(artistId)
e6ccfeca 397 print "Saved radio"
3fcef5ba 398 return self.saveRadio(radio = radio)
8817bb2e 399 else:
e6ccfeca 400 print "Failed to get radio"
3fcef5ba 401 return False
8817bb2e 402
3fcef5ba 403 def radioSong(self, songId = None):
404 radio = self.getSavedRadio()
405 if radio != None and songId != None:
406 try:
407 radio['seedSongs'].remove(songId)
408 except: pass
409 radio['seedSongs'].append(songId)
e6ccfeca 410 print "Saved radio"
3fcef5ba 411 return self.saveRadio(radio = radio)
412 else:
e6ccfeca 413 print "Failed to get radio"
3fcef5ba 414 return False
8817bb2e 415
416 def radioTurnedOn(self):
417 return self.radioEnabled
418
3fcef5ba 419 def getSavedRadio(self):
420 path = os.path.join(self.confDir, 'radio', 'radio.dmp')
b738088f 421 try:
422 f = open(path, 'rb')
423 radio = pickle.load(f)
424 f.close()
3fcef5ba 425 print radio
b738088f 426 except:
e6ccfeca 427 print "Failed to open " + path
3fcef5ba 428 radio = {}
429 radio['seedSongs'] = []
430 radio['seedArtists'] = []
431 radio['frowns'] = []
432 if self.saveRadio(radio) == False:
433 return None
b738088f 434 return radio
435
3fcef5ba 436 def saveRadio(self, radio): #blaher
437 if radio == {}:
438 print 'Invalid radio'
439 return False
b738088f 440 try:
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):
444 os.mkdir(dir)
3fcef5ba 445 path = os.path.join(dir, 'radio.dmp')
b738088f 446 f = open(path, 'wb')
447 pickle.dump(radio, f, protocol=pickle.HIGHEST_PROTOCOL)
448 f.close()
3fcef5ba 449 return True
b738088f 450 except IOError, e:
451 print 'There was an error while saving the radio pickle (%s)' % e
3fcef5ba 452 return False
b738088f 453 except:
3fcef5ba 454 print "An unknown error occurred during save radio: " + str(sys.exc_info()[0])
455 return False
b738088f 456
8817bb2e 457 def favoriteSong(self, songID):
458 return self.callRemote("song.favorite", {"songID": songID})
459
460 def unfavoriteSong(self, songID):
461 return self.callRemote("song.unfavorite", {"songID": songID})
462
463 def getMethods(self):
464 return self.callRemote("service.getMethods")
465
466 def searchSongsExactMatch(self, songName, artistName, albumName):
467 result = self.callRemote("search.songExactMatch", {"songName": songName, "artistName": artistName, "albumName": albumName})
468 list = self.parseSongs(result)
469 return list
470
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)
474 return list
475 #return sorted(list, key=itemgetter(sortKey))
476
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)
480 return list
481 #return sorted(list, key=itemgetter(sortKey))
482
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)
486 return list
487 #return sorted(list, key=itemgetter(sortKey))
488
489 def searchPlaylists(self, query, limit):
490 result = self.callRemote("search.playlists", {"query": query, "limit": limit, "streamableOnly": 1})
491 list = self.parsePlaylists(result)
492 return list
493
494 def popularGetSongs(self, limit):
495 result = self.callRemote("popular.getSongs", {"limit": limit})
496 list = self.parseSongs(result)
497 return list
498
499 def popularGetArtists(self, limit):
500 result = self.callRemote("popular.getArtists", {"limit": limit})
501 list = self.parseArtists(result)
502 return list
503
504 def popularGetAlbums(self, limit):
505 result = self.callRemote("popular.getAlbums", {"limit": limit})
506 list = self.parseAlbums(result)
507 return list
508
b738088f 509 def artistAbout(self, artistId):
510 result = self.callRemote("artist.about", {"artistID": artistId})
511 return result
512
8817bb2e 513 def artistGetAlbums(self, artistId, limit, sortKey=2):
514 result = self.callRemote("artist.getAlbums", {"artistID": artistId, "limit": limit})
515 list = self.parseAlbums(result)
516 return list
517 #return sorted(list, key=itemgetter(sortKey))
518
519 def artistGetVerifiedAlbums(self, artistId, limit):
520 result = self.callRemote("artist.getVerifiedAlbums", {"artistID": artistId, "limit": limit})
521 list = self.parseSongs(result)
522 return list
523
524 def albumGetSongs(self, albumId, limit):
525 result = self.callRemote("album.getSongs", {"albumID": albumId, "limit": limit})
526 list = self.parseSongs(result)
527 return list
528
529 def songGetSimilar(self, songId, limit):
530 result = self.callRemote("song.getSimilar", {"songID": songId, "limit": limit})
531 list = self.parseSongs(result)
532 return list
533
b738088f 534 def artistGetSimilar(self, artistId, limit):
535 result = self.callRemote("artist.getSimilar", {"artistID": artistId, "limit": limit})
536 list = self.parseArtists(result)
537 return list
538
539 def songAbout(self, songId):
540 result = self.callRemote("song.about", {"songID": songId})
541 return result['result']['song']
542
543 def getVersion(self):
544 result = self.callRemote("service.getVersion", {})
545 return result
546
8817bb2e 547 def parseSongs(self, items):
548 try:
549 if 'result' in items:
550 i = 0
551 list = []
552 if 'songs' in items['result']:
553 l = len(items['result']['songs'])
554 index = 'songs'
555 elif 'song' in items['result']:
556 l = 1
557 index = 'song'
558 else:
559 l = 0
560 index = ''
561 while(i < l):
562 if index == 'songs':
563 s = items['result'][index][i]
564 else:
565 s = items['result'][index]
566 if 'estDurationSecs' in s:
567 dur = s['estDurationSecs']
568 else:
569 dur = 0
570 try:
571 notIn = True
572 for entry in list:
573 songName = s['songName'].encode('ascii', 'ignore')
574 albumName = s['albumName'].encode('ascii', 'ignore')
575 artistName = s['artistName'].encode('ascii', 'ignore')
b738088f 576 if self.removeDuplicates == True:
577 if (entry[0].lower() == songName.lower()) and (entry[3].lower() == albumName.lower()) and (entry[6].lower() == artistName.lower()):
578 notIn = False
8817bb2e 579 if notIn == True:
580 list.append([s['songName'].encode('ascii', 'ignore'),\
581 s['songID'],\
582 dur,\
583 s['albumName'].encode('ascii', 'ignore'),\
584 s['albumID'],\
585 s['image']['tiny'].encode('ascii', 'ignore'),\
586 s['artistName'].encode('ascii', 'ignore'),\
587 s['artistID'],\
588 s['image']['small'].encode('ascii', 'ignore'),\
589 s['image']['medium'].encode('ascii', 'ignore')])
590 except:
591 print 'GrooveShark: Could not parse song number: ' + str(i)
592 traceback.print_exc()
593 i = i + 1
594 return list
595 else:
596 return []
597 pass
598 except:
599 print 'GrooveShark: Could not parse songs. Got this:'
600 traceback.print_exc()
601 return []
602
603 def parseArtists(self, items):
b738088f 604 try:
605 if 'result' in items:
606 i = 0
607 list = []
608 artists = items['result']['artists']
609 while(i < len(artists)):
610 s = artists[i]
611 try:
612 list.append([s['artistName'].encode('ascii', 'ignore'),\
613 s['artistID']])
614 except:
615 print 'GrooveShark: Could not parse album number: ' + str(i)
616 traceback.print_exc()
617 i = i + 1
618 return list
619 else:
620 return []
621 except:
622 print 'GrooveShark: Could not parse artists. Got this:'
623 traceback.print_exc()
8817bb2e 624 return []
625
626 def parseAlbums(self, items):
b738088f 627 try:
628 if 'result' in items:
629 i = 0
630 list = []
631 albums = items['result']['albums']
632 while(i < len(albums)):
633 s = albums[i]
634 try: # Avoid ascii ancoding errors
635 list.append([s['artistName'].encode('ascii', 'ignore'),\
636 s['artistID'],\
637 s['albumName'].encode('ascii', 'ignore'),\
638 s['albumID'],\
406ab447 639 s['image']['medium'].encode('ascii', 'ignore')])
b738088f 640 except:
641 print 'GrooveShark: Could not parse album number: ' + str(i)
642 traceback.print_exc()
643 i = i + 1
644 return list
645 else:
646 return []
647 except:
648 print 'GrooveShark: Could not parse albums. Got this'
649 traceback.print_exc()
8817bb2e 650 return []
651
652 def parsePlaylists(self, items):
b738088f 653 try:
654 if 'result' in items:
655 i = 0
656 list = []
657 playlists = items['result']['playlists']
658 while(i < len(playlists)):
659 s = playlists[i]
660 try: # Avoid ascii ancoding errors
661 list.append([s['playlistID'],\
662 s['playlistName'].encode('ascii', 'ignore'),\
663 s['username'].encode('ascii', 'ignore')])
664 except:
665 print 'GrooveShark: Could not parse playlist number: ' + str(i)
666 traceback.print_exc()
667 i = i + 1
668 return list
669 else:
670 return []
671 except:
672 print 'GrooveShark: Could not parse playlists. Got this:'
673 print items
8817bb2e 674 return []