Some playlist updates.
[clinton/xbmc-groove.git] / resources / lib / GrooveAPI.py
index 5cc37f7..ed22a24 100644 (file)
@@ -27,14 +27,14 @@ class GrooveAPI:
                socket.setdefaulttimeout(timeout)
                self.enableDebug = enableDebug
                self.loggedIn = 0
                socket.setdefaulttimeout(timeout)
                self.enableDebug = enableDebug
                self.loggedIn = 0
-               self.radioEnabled = 0
                self.userId = 0
                self.userId = 0
-               self.seedArtists = []
-               self.frowns = []
-               self.songIDsAlreadySeen = []
-               self.recentArtists = []
                self.removeDuplicates = False
                self.removeDuplicates = False
-               self.dataDir = 'plugin_data/music/'
+
+               self.radioRecentSongs = []
+               self.radioRecentArtists = []
+               self.radioEnabled = False
+
+               self.dataDir = 'addon_data'
                self.confDir = xbmc.translatePath(os.path.join('special://masterprofile/' + self.dataDir, os.path.basename(os.getcwd())))
                self.sessionID = self.getSavedSession()
                self.debug('Saved sessionID: ' + self.sessionID)
                self.confDir = xbmc.translatePath(os.path.join('special://masterprofile/' + self.dataDir, os.path.basename(os.getcwd())))
                self.sessionID = self.getSavedSession()
                self.debug('Saved sessionID: ' + self.sessionID)
@@ -152,7 +152,7 @@ class GrooveAPI:
                if 'fault' in result:
                        return ''
                else:
                if 'fault' in result:
                        return ''
                else:
-                       return result['header']['sessionID']
+                       return result['result']['sessionID']
 
        def sessionDestroy(self):
                return self.callRemote("session.destroy")
 
        def sessionDestroy(self):
                return self.callRemote("session.destroy")
@@ -284,6 +284,16 @@ class GrooveAPI:
                                return 0
                else:
                        return 0
                                return 0
                else:
                        return 0
+
+       def playlistCreateUnique(self, name, songIds):
+               if self.loggedIn == 1:
+                       result = self.callRemote("playlist.createunique", {"name": name, "songIDs": songIds})
+                       if 'result' in result:
+                               return result['result']['playlistID']
+                       else:
+                               return 0
+               else:
+                       return 0
                        
        def playlistGetSongs(self, playlistId, limit=25):
                result = self.callRemote("playlist.getSongs", {"playlistID": playlistId})
                        
        def playlistGetSongs(self, playlistId, limit=25):
                result = self.callRemote("playlist.getSongs", {"playlistID": playlistId})
@@ -317,6 +327,16 @@ class GrooveAPI:
                                return 1
                else:
                        return 0
                                return 1
                else:
                        return 0
+               
+       def playlistDeleteSong(self, playlistId, position):
+               if self.loggedIn == 1:
+                       result = self.callRemote("playlist.removeSong", {"playlistID": playlistId, "position": position})
+                       if 'fault' in result:
+                               return 0
+                       else:
+                               return 1
+               else:
+                       return 0
                        
        def playlistReplace(self, playlistId, songIds):
                if self.loggedIn == 1:
                        
        def playlistReplace(self, playlistId, songIds):
                if self.loggedIn == 1:
@@ -328,127 +348,121 @@ class GrooveAPI:
                else:
                        return 0
 
                else:
                        return 0
 
-       def autoplayStartWithArtistIDs(self, artistIds):
-               result = self.callRemote("autoplay.startWithArtistIDs", {"artistIDs": artistIds})
-               if 'fault' in result:
-                       self.radioEnabled = 0
-                       return 0
-               else:
-                       self.radioEnabled = 1
-                       return 1                
-
-       def autoplayStart(self, songIds):
-               result = self.callRemote("autoplay.start", {"songIDs": songIds})
+       def radioStartArtists(self):
+               radio = self.getSavedRadio()
+               if radio == None:
+                       return False
+               result = self.callRemote("autoplay.startWithArtistIDs", {"artistIDs": radio['seedArtists']})
                if 'fault' in result:
                if 'fault' in result:
-                       self.radioEnabled = 0
-                       return 0
+                       print "Cannot autoplay artists"
+                       self.radioEnabled = False
                else:
                else:
-                       self.radioEnabled = 1
-                       return 1
+                       self.radioEnabled = True
+               return self.radioEnabled
 
 
-       def autoplayGetNextSongEx(self, seedArtists = [], frowns = [], songIDsAlreadySeen = [], recentArtists = []):
-               result = self.callRemote("autoplay.getNextSongEx", {"seedArtists": seedArtists, "frowns": frowns, "songIDsAlreadySeen": songIDsAlreadySeen, "recentArtists": recentArtists})
+       def radioStartSongs(self):
+               radio = self.getSavedRadio()
+               if radio == None:
+                       return False
+               result = self.callRemote("autoplay.start", {"songIDs": radio['seedSongs']})
                if 'fault' in result:
                if 'fault' in result:
-                       return []
+                       print "Cannot autoplay songs"
+                       self.radioEnabled = False
                else:
                else:
-                       return result
+                       self.radioEnabled = True
+               return self.radioEnabled
        
        
-       def radioGetNextSong(self):
+       def radioNextSong(self):
                radio = self.getSavedRadio()
                if radio == None:
                        return None
                else:
                radio = self.getSavedRadio()
                if radio == None:
                        return None
                else:
-                       seedArtists = []
-                       for song in radio['seedArtists']:
-                               seedArtists.append(song[7])
-                       result = self.autoplayGetNextSongEx(seedArtists, radio['frowns'], radio['songIDsAlreadySeen'], radio['recentArtists'])
+                       result = self.callRemote("autoplay.getNextSongEx", {"seedArtists": radio['seedArtists'], "frowns": radio['frowns'], "songIDsAlreadySeen": self.radioRecentSongs, "recentArtists": self.radioRecentArtists})
                        if 'fault' in result:
                                return []
                        else:
                                song = self.parseSongs(result)
                        if 'fault' in result:
                                return []
                        else:
                                song = self.parseSongs(result)
-                               self.radioSetAlreadyListenedSong(songId = song[0][1])
+                               self.radioRecentSongs.append(song[0][1])
+                               self.radioRecentArtists.append(song[0][7])
                                return song
 
                                return song
 
-       def radioFrown(self, songId):
-               self.frown.append(songId)
-
-       def radioAlreadySeen(self, songId):
-               self.songIDsAlreadySeen.append(songId)
-
-       def radioAddArtist(self, song = None, radioName = None):
-               radio = self.getSavedRadio(name = radioName)
-               if radio != None and song != None:
-                       radio['seedArtists'].append(song)
+       def radioFrown(self, songId = None):
+               radio = self.getSavedRadio()
+               if radio != None and songId != None:
+                       try:
+                               radio['frowns'].remove(songId)
+                       except: pass
+                       radio['frowns'].append(songId)
                        return self.saveRadio(radio = radio)
                else:
                        return self.saveRadio(radio = radio)
                else:
-                       return 0
+                       return False
 
 
-       def radioStart(self, artists = [], frowns = []):
-               for artist in artists:
-                       self.seedArtists.append(artist)
-               for artist in frowns:
-                       self.frowns.append(artist)
-               if self.autoplayStartWithArtistIDs(self.seedArtists) == 1:
-                       self.radioEnabled = 1
-                       return 1
+       def radioArtist(self, artistId = None):
+               radio = self.getSavedRadio()
+               if radio != None and artistId != None:
+                       try:
+                               radio['seedArtists'].remove(artistId)
+                       except: pass
+                       radio['seedArtists'].append(artistId)
+                       print "Saved radio"
+                       return self.saveRadio(radio = radio)
                else:
                else:
-                       self.radioEnabled = 0
-                       return 0
+                       print "Failed to get radio"
+                       return False
 
 
-       def radioStop(self):
-               self.seedArtists = []
-               self.frowns = []
-               self.songIDsAlreadySeen = []
-               self.recentArtists = []
-               self.radioEnabled = 0
+       def radioSong(self, songId = None):
+               radio = self.getSavedRadio()
+               if radio != None and songId != None:
+                       try:
+                               radio['seedSongs'].remove(songId)
+                       except: pass
+                       radio['seedSongs'].append(songId)
+                       print "Saved radio"
+                       return self.saveRadio(radio = radio)
+               else:
+                       print "Failed to get radio"
+                       return False
 
        def radioTurnedOn(self):
                return self.radioEnabled
 
 
        def radioTurnedOn(self):
                return self.radioEnabled
 
-       def radioSetAlreadyListenedSong(self, name = None, songId = ''):
-               radio = self.getSavedRadio(name = name)
-               if radio != None and songId != '':
-                       radio['songIDsAlreadySeen'].append(songId)
-                       while len(radio['songIDsAlreadySeen']) > 20:
-                               radio['songIDsAlreadySeen'].pop(0) # Trim
-                       return self.saveRadio(radio = radio)
-               else:
-                       return 0
-
-       def getSavedRadio(self, name = None):
-               if name == None:
-                       path = os.path.join(self.confDir, 'radio', 'default.txt')
-               else:
-                       path = os.path.join(self.confDir, 'radio', 'saved', name)
+       def getSavedRadio(self):
+               path = os.path.join(self.confDir, 'radio', 'radio.dmp')
                try:
                        f = open(path, 'rb')
                        radio = pickle.load(f)
                        f.close()
                try:
                        f = open(path, 'rb')
                        radio = pickle.load(f)
                        f.close()
+                       print radio
                except:
                except:
-                       radio = None
+                       print "Failed to open " + path
+                       radio = {}
+                       radio['seedSongs'] = []
+                       radio['seedArtists'] = []
+                       radio['frowns'] = []
+                       if self.saveRadio(radio) == False:
+                               return None
                return radio
 
                return radio
 
-       def saveRadio(self, name = None, radio = {}): #blaher
+       def saveRadio(self, radio): #blaher
+               if radio == {}:
+                       print 'Invalid radio'
+                       return False
                try:
                        dir = os.path.join(self.confDir, 'radio')
                        # Create the 'data' directory if it doesn't exist.
                        if not os.path.exists(dir):
                                os.mkdir(dir)
                try:
                        dir = os.path.join(self.confDir, 'radio')
                        # Create the 'data' directory if it doesn't exist.
                        if not os.path.exists(dir):
                                os.mkdir(dir)
-                               os.mkdir(os.path.join(dir, 'saved'))
-                       if name == None:
-                               path = os.path.join(dir, 'default.txt')
-                       else:
-                               path = os.path.join(dir, 'saved', name)
+                       path = os.path.join(dir, 'radio.dmp')
                        f = open(path, 'wb')
                        pickle.dump(radio, f, protocol=pickle.HIGHEST_PROTOCOL)
                        f.close()
                        f = open(path, 'wb')
                        pickle.dump(radio, f, protocol=pickle.HIGHEST_PROTOCOL)
                        f.close()
-                       return 1
+                       return True
                except IOError, e:
                        print 'There was an error while saving the radio pickle (%s)' % e
                except IOError, e:
                        print 'There was an error while saving the radio pickle (%s)' % e
-                       return 0
+                       return False
                except:
                except:
-                       print "An unknown error occured during save radio: " + str(sys.exc_info()[0])
-                       return 0
+                       print "An unknown error occurred during save radio: " + str(sys.exc_info()[0])
+                       return False
 
        def favoriteSong(self, songID):
                return self.callRemote("song.favorite", {"songID": songID})
 
        def favoriteSong(self, songID):
                return self.callRemote("song.favorite", {"songID": songID})
@@ -632,7 +646,7 @@ class GrooveAPI:
                                                s['artistID'],\
                                                s['albumName'].encode('ascii', 'ignore'),\
                                                s['albumID'],\
                                                s['artistID'],\
                                                s['albumName'].encode('ascii', 'ignore'),\
                                                s['albumID'],\
-                                               s['image']['tiny'].encode('ascii', 'ignore')])
+                                               s['image']['medium'].encode('ascii', 'ignore')])
                                        except:
                                                print 'GrooveShark: Could not parse album number: ' + str(i)
                                                traceback.print_exc()
                                        except:
                                                print 'GrooveShark: Could not parse album number: ' + str(i)
                                                traceback.print_exc()