e97d04dbd415221a34d67d7a2346421819d9ed11
[clinton/xbmc-groove.git] / resources / lib / GrooveAPI.py
1 import urllib2, md5, unicodedata, re, os, traceback, sys, pickle, socket, xbmc
2 from operator import itemgetter, attrgetter
3
4 class 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
10 class 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
16 class 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
22 class GrooveAPI:
23 def __init__(self, enableDebug = False, isXbox = False):
24 import simplejson
25 self.simplejson = simplejson
26 timeout = 40
27 socket.setdefaulttimeout(timeout)
28 self.enableDebug = enableDebug
29 self.loggedIn = 0
30 self.userId = 0
31 self.removeDuplicates = False
32
33 self.radioRecentSongs = []
34 self.radioRecentArtists = []
35 self.radioEnabled = False
36
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()
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
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
70
71 def getSavedSession(self):
72 sessionID = ''
73 path = os.path.join(self.confDir, 'session', 'session.txt')
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:
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):
90 os.makedirs(dir)
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:
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):
107 os.makedirs(dir)
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}
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)))
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)
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 []
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:
155 return result['result']['sessionID']
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
218
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
287
288 def playlistGetSongs(self, playlistId, limit=25):
289 result = self.callRemote("playlist.getSongs", {"playlistID": playlistId})
290 list = self.parseSongs(result)
291 return list
292
293 def playlistDelete(self, playlistId):
294 if self.loggedIn == 1:
295 return self.callRemote("playlist.delete", {"playlistID": playlistId})
296
297 def playlistRename(self, playlistId, name):
298 if self.loggedIn == 1:
299 result = self.callRemote("playlist.rename", {"playlistID": playlistId, "name": name})
300 if 'fault' in result:
301 return 0
302 else:
303 return 1
304 else:
305 return 0
306
307 def playlistClearSongs(self, playlistId):
308 if self.loggedIn == 1:
309 return self.callRemote("playlist.clearSongs", {"playlistID": playlistId})
310
311 def playlistAddSong(self, playlistId, songId, position):
312 if self.loggedIn == 1:
313 result = self.callRemote("playlist.addSong", {"playlistID": playlistId, "songID": songId, "position": position})
314 if 'fault' in result:
315 return 0
316 else:
317 return 1
318 else:
319 return 0
320
321 def playlistReplace(self, playlistId, songIds):
322 if self.loggedIn == 1:
323 result = self.callRemote("playlist.replace", {"playlistID": playlistId, "songIDs": songIds})
324 if 'fault' in result:
325 return 0
326 else:
327 return 1
328 else:
329 return 0
330
331 def radioStartArtists(self):
332 radio = self.getSavedRadio()
333 if radio == None:
334 return False
335 result = self.callRemote("autoplay.startWithArtistIDs", {"artistIDs": radio['seedArtists']})
336 if 'fault' in result:
337 self.radioEnabled = False
338 else:
339 self.radioEnabled = True
340 return self.radioEnabled
341
342 def radioStartSongs(self):
343 radio = self.getSavedRadio()
344 if radio == None:
345 return False
346 result = self.callRemote("autoplay.start", {"songIDs": radio['seedSongs']})
347 if 'fault' in result:
348 self.radioEnabled = False
349 else:
350 self.radioEnabled = True
351 return self.radioEnabled
352
353 def radioNextSong(self):
354 radio = self.getSavedRadio()
355 if radio == None:
356 return None
357 else:
358 result = self.callRemote("autoplay.getNextSongEx", {"seedArtists": radio['seedArtists'], "frowns": radio['frowns'], "songIDsAlreadySeen": self.radioRecentSongs, "recentArtists": self.radioRecentArtists})
359 if 'fault' in result:
360 return []
361 else:
362 song = self.parseSongs(result)
363 self.radioRecentSongs.append(song[0][1])
364 self.radioRecentArtists.append(song[0][7])
365 return song
366
367 def radioFrown(self, songId = None):
368 radio = self.getSavedRadio()
369 if radio != None and songId != None:
370 try:
371 radio['frowns'].remove(songId)
372 except: pass
373 radio['frowns'].append(songId)
374 return self.saveRadio(radio = radio)
375 else:
376 return False
377
378 def radioArtist(self, artistId = None):
379 radio = self.getSavedRadio()
380 if radio != None and artistId != None:
381 try:
382 radio['seedArtists'].remove(artistId)
383 except: pass
384 radio['seedArtists'].append(artistId)
385 return self.saveRadio(radio = radio)
386 else:
387 return False
388
389 def radioSong(self, songId = None):
390 radio = self.getSavedRadio()
391 if radio != None and songId != None:
392 try:
393 radio['seedSongs'].remove(songId)
394 except: pass
395 radio['seedSongs'].append(songId)
396 return self.saveRadio(radio = radio)
397 else:
398 return False
399
400 def radioTurnedOn(self):
401 return self.radioEnabled
402
403 def getSavedRadio(self):
404 path = os.path.join(self.confDir, 'radio', 'radio.dmp')
405 try:
406 f = open(path, 'rb')
407 radio = pickle.load(f)
408 f.close()
409 print radio
410 except:
411 radio = {}
412 radio['seedSongs'] = []
413 radio['seedArtists'] = []
414 radio['frowns'] = []
415 if self.saveRadio(radio) == False:
416 return None
417 return radio
418
419 def saveRadio(self, radio): #blaher
420 if radio == {}:
421 print 'Invalid radio'
422 return False
423 try:
424 dir = os.path.join(self.confDir, 'radio')
425 # Create the 'data' directory if it doesn't exist.
426 if not os.path.exists(dir):
427 os.mkdir(dir)
428 path = os.path.join(dir, 'radio.dmp')
429 f = open(path, 'wb')
430 pickle.dump(radio, f, protocol=pickle.HIGHEST_PROTOCOL)
431 f.close()
432 return True
433 except IOError, e:
434 print 'There was an error while saving the radio pickle (%s)' % e
435 return False
436 except:
437 print "An unknown error occurred during save radio: " + str(sys.exc_info()[0])
438 return False
439
440 def favoriteSong(self, songID):
441 return self.callRemote("song.favorite", {"songID": songID})
442
443 def unfavoriteSong(self, songID):
444 return self.callRemote("song.unfavorite", {"songID": songID})
445
446 def getMethods(self):
447 return self.callRemote("service.getMethods")
448
449 def searchSongsExactMatch(self, songName, artistName, albumName):
450 result = self.callRemote("search.songExactMatch", {"songName": songName, "artistName": artistName, "albumName": albumName})
451 list = self.parseSongs(result)
452 return list
453
454 def searchSongs(self, query, limit, page=0, sortKey=6):
455 result = self.callRemote("search.songs", {"query": query, "limit": limit, "page:": page, "streamableOnly": 1})
456 list = self.parseSongs(result)
457 return list
458 #return sorted(list, key=itemgetter(sortKey))
459
460 def searchArtists(self, query, limit, sortKey=0):
461 result = self.callRemote("search.artists", {"query": query, "limit": limit, "streamableOnly": 1})
462 list = self.parseArtists(result)
463 return list
464 #return sorted(list, key=itemgetter(sortKey))
465
466 def searchAlbums(self, query, limit, sortKey=2):
467 result = self.callRemote("search.albums", {"query": query, "limit": limit, "streamableOnly": 1})
468 list = self.parseAlbums(result)
469 return list
470 #return sorted(list, key=itemgetter(sortKey))
471
472 def searchPlaylists(self, query, limit):
473 result = self.callRemote("search.playlists", {"query": query, "limit": limit, "streamableOnly": 1})
474 list = self.parsePlaylists(result)
475 return list
476
477 def popularGetSongs(self, limit):
478 result = self.callRemote("popular.getSongs", {"limit": limit})
479 list = self.parseSongs(result)
480 return list
481
482 def popularGetArtists(self, limit):
483 result = self.callRemote("popular.getArtists", {"limit": limit})
484 list = self.parseArtists(result)
485 return list
486
487 def popularGetAlbums(self, limit):
488 result = self.callRemote("popular.getAlbums", {"limit": limit})
489 list = self.parseAlbums(result)
490 return list
491
492 def artistAbout(self, artistId):
493 result = self.callRemote("artist.about", {"artistID": artistId})
494 return result
495
496 def artistGetAlbums(self, artistId, limit, sortKey=2):
497 result = self.callRemote("artist.getAlbums", {"artistID": artistId, "limit": limit})
498 list = self.parseAlbums(result)
499 return list
500 #return sorted(list, key=itemgetter(sortKey))
501
502 def artistGetVerifiedAlbums(self, artistId, limit):
503 result = self.callRemote("artist.getVerifiedAlbums", {"artistID": artistId, "limit": limit})
504 list = self.parseSongs(result)
505 return list
506
507 def albumGetSongs(self, albumId, limit):
508 result = self.callRemote("album.getSongs", {"albumID": albumId, "limit": limit})
509 list = self.parseSongs(result)
510 return list
511
512 def songGetSimilar(self, songId, limit):
513 result = self.callRemote("song.getSimilar", {"songID": songId, "limit": limit})
514 list = self.parseSongs(result)
515 return list
516
517 def artistGetSimilar(self, artistId, limit):
518 result = self.callRemote("artist.getSimilar", {"artistID": artistId, "limit": limit})
519 list = self.parseArtists(result)
520 return list
521
522 def songAbout(self, songId):
523 result = self.callRemote("song.about", {"songID": songId})
524 return result['result']['song']
525
526 def getVersion(self):
527 result = self.callRemote("service.getVersion", {})
528 return result
529
530 def parseSongs(self, items):
531 try:
532 if 'result' in items:
533 i = 0
534 list = []
535 if 'songs' in items['result']:
536 l = len(items['result']['songs'])
537 index = 'songs'
538 elif 'song' in items['result']:
539 l = 1
540 index = 'song'
541 else:
542 l = 0
543 index = ''
544 while(i < l):
545 if index == 'songs':
546 s = items['result'][index][i]
547 else:
548 s = items['result'][index]
549 if 'estDurationSecs' in s:
550 dur = s['estDurationSecs']
551 else:
552 dur = 0
553 try:
554 notIn = True
555 for entry in list:
556 songName = s['songName'].encode('ascii', 'ignore')
557 albumName = s['albumName'].encode('ascii', 'ignore')
558 artistName = s['artistName'].encode('ascii', 'ignore')
559 if self.removeDuplicates == True:
560 if (entry[0].lower() == songName.lower()) and (entry[3].lower() == albumName.lower()) and (entry[6].lower() == artistName.lower()):
561 notIn = False
562 if notIn == True:
563 list.append([s['songName'].encode('ascii', 'ignore'),\
564 s['songID'],\
565 dur,\
566 s['albumName'].encode('ascii', 'ignore'),\
567 s['albumID'],\
568 s['image']['tiny'].encode('ascii', 'ignore'),\
569 s['artistName'].encode('ascii', 'ignore'),\
570 s['artistID'],\
571 s['image']['small'].encode('ascii', 'ignore'),\
572 s['image']['medium'].encode('ascii', 'ignore')])
573 except:
574 print 'GrooveShark: Could not parse song number: ' + str(i)
575 traceback.print_exc()
576 i = i + 1
577 return list
578 else:
579 return []
580 pass
581 except:
582 print 'GrooveShark: Could not parse songs. Got this:'
583 traceback.print_exc()
584 return []
585
586 def parseArtists(self, items):
587 try:
588 if 'result' in items:
589 i = 0
590 list = []
591 artists = items['result']['artists']
592 while(i < len(artists)):
593 s = artists[i]
594 try:
595 list.append([s['artistName'].encode('ascii', 'ignore'),\
596 s['artistID']])
597 except:
598 print 'GrooveShark: Could not parse album number: ' + str(i)
599 traceback.print_exc()
600 i = i + 1
601 return list
602 else:
603 return []
604 except:
605 print 'GrooveShark: Could not parse artists. Got this:'
606 traceback.print_exc()
607 return []
608
609 def parseAlbums(self, items):
610 try:
611 if 'result' in items:
612 i = 0
613 list = []
614 albums = items['result']['albums']
615 while(i < len(albums)):
616 s = albums[i]
617 try: # Avoid ascii ancoding errors
618 list.append([s['artistName'].encode('ascii', 'ignore'),\
619 s['artistID'],\
620 s['albumName'].encode('ascii', 'ignore'),\
621 s['albumID'],\
622 s['image']['tiny'].encode('ascii', 'ignore')])
623 except:
624 print 'GrooveShark: Could not parse album number: ' + str(i)
625 traceback.print_exc()
626 i = i + 1
627 return list
628 else:
629 return []
630 except:
631 print 'GrooveShark: Could not parse albums. Got this'
632 traceback.print_exc()
633 return []
634
635 def parsePlaylists(self, items):
636 try:
637 if 'result' in items:
638 i = 0
639 list = []
640 playlists = items['result']['playlists']
641 while(i < len(playlists)):
642 s = playlists[i]
643 try: # Avoid ascii ancoding errors
644 list.append([s['playlistID'],\
645 s['playlistName'].encode('ascii', 'ignore'),\
646 s['username'].encode('ascii', 'ignore')])
647 except:
648 print 'GrooveShark: Could not parse playlist number: ' + str(i)
649 traceback.print_exc()
650 i = i + 1
651 return list
652 else:
653 return []
654 except:
655 print 'GrooveShark: Could not parse playlists. Got this:'
656 print items
657 return []