示例#1
0
 def _api_request(self, endpoint, params=None, method="get"):
     '''get info from json api'''
     result = {}
     url = "https://api.spotify.com/v1/%s" % endpoint
     params = params if params else {}
     try:
         headers = {"Authorization": "Bearer %s" % self._token["accessToken"]}
         if method == "post":
             response = requests.post(url, json=params, headers=headers, timeout=10)
         elif method == "put":
             response = requests.put(url, json=params, headers=headers, timeout=10)
         else:
             response = requests.get(url, params=params, headers=headers, timeout=10)
         if response and response.content and response.status_code == 200:
             if "{" in response.content:
                 result = json.loads(response.content.decode('utf-8', 'replace'))
             else:
                 result = response.content.decode('utf-8')
         else:
             LOGGER.error("Invalid or empty reponse from server - endpoint: %s - server response: %s - %s" %
                     (endpoint, response.status_code, response.content))
     except Exception as exc:
         if self.monitor.config["ENABLE_DEBUG"]:
             LOGGER.error(exc)
         result = None
     return result
示例#2
0
 def _parseconfig(self):
     ''' get config from player's json configfile'''
     try:
         with open(CONFIG_FILE) as json_file:
             json_data = json_file.read()
             config = json.loads(json_data.decode("utf-8"))
     except Exception as exc:
         # Error while reading config file, starting with defaults...
         config = {}
     result = ConfigDict([
         ("STARTUP_VOLUME", config.get("STARTUP_VOLUME", 0)),
         ("NOTIFY_VOLUME", config.get("NOTIFY_VOLUME", 40)),
         ("ALERT_VOLUME", config.get("ALERT_VOLUME", 70)),
         ("VOLUME_LIMITER", config.get("VOLUME_LIMITER", 0)),
         ("VOLUME_LIMITER_MORNING", config.get("VOLUME_LIMITER_MORNING",
                                               0)),
         ("ENABLE_DEBUG", config.get("ENABLE_DEBUG", False)),
         ("AUTO_UPDATE_ON_STARTUP",
          config.get("AUTO_UPDATE_ON_STARTUP", True))
     ])
     # append other config keys which are set by modules
     for key, value in config.items():
         if key not in result:
             result[key] = value
     # save first config file
     if not os.path.isfile(CONFIG_FILE):
         with open(CONFIG_FILE, "w") as json_file:
             json_file.write(result.json)
     return result
示例#3
0
    def _on_message(self, mosq, obj, msg):
        """
        Handle incoming messages
        """
        topicparts = msg.topic.split("/")
        # some magic to found out the target and command
        if "/".join(topicparts[:-1]) == self.config["MQTT_TOPIC_COMMAND"]:
            target = topicparts[-1]
            command = msg.payload
        elif "/".join(topicparts[:-2]) == self.config["MQTT_TOPIC_COMMAND"]:
            target = topicparts[-2]
            command = topicparts[-1]

        else:
            target = None
            command = None
        if not target or not command:
            LOGGER.debug(
                "Received MQTT message in invalid format --> topic: %s - payload: %s"
                % (msg.topic, msg.payload))
        else:
            opt_data = msg.payload.decode("utf-8")
            try:
                opt_data = json.loads(opt_data.decode("utf-8"))
            except:
                pass
            LOGGER.debug(
                "Received command --> target: %s - command: %s - opt_data: %s"
                % (target, command, opt_data))
            self.monitor.command(target, command, opt_data)
示例#4
0
    def onNotification(self, sender, method, data):
        '''builtin function for the xbmc.Monitor class'''
        try:
            log_msg("Kodi_Monitor: sender %s - method: %s  - data: %s" %
                    (sender, method, data))
            data = json.loads(try_decode(data))
            mediatype = ""
            dbid = 0
            transaction = False
            if data and isinstance(data, dict):
                if data.get("item"):
                    mediatype = data["item"].get("type", "")
                    dbid = data["item"].get("id", 0)
                elif data.get("type"):
                    mediatype = data["type"]
                    dbid = data.get("id", 0)
                if data.get("transaction"):
                    transaction = True

            if method == "System.OnQuit":
                self.win.setProperty("SkinHelperShutdownRequested", "shutdown")

            if method == "VideoLibrary.OnUpdate":
                self.process_db_update(mediatype, dbid, transaction)

            if method == "AudioLibrary.OnUpdate":
                self.process_db_update(mediatype, dbid, transaction)

            if method == "Player.OnStop":
                self.monitoring_stream = False
                self.infopanelshown = False
                self.win.clearProperty("Skinhelper.PlayerPlaying")
                self.win.clearProperty("TrailerPlaying")
                self.reset_win_props()

            if method == "Player.OnPlay":
                if not self.monitoring_stream and not getCondVisibility(
                        "Player.DisplayAfterSeek"):
                    self.reset_win_props()
                if self.wait_for_player():
                    if getCondVisibility("Player.HasAudio"):
                        if getCondVisibility("Player.IsInternetStream"):
                            self.monitor_radiostream()
                        else:
                            self.set_music_properties()
                    if getCondVisibility("Pvr.IsPlayingRadio"):
                        if getCondVisibility("!Player.IsInternetStream"):
                            self.monitor_radiostream()
                        else:
                            self.set_music_properties()
                    elif getCondVisibility(
                            "VideoPlayer.Content(livetv) | String.StartsWith(Player.FileNameAndPath,pvr://)"
                    ):
                        self.monitor_livetv()
                    else:
                        self.set_video_properties(mediatype, dbid)
                        self.show_info_panel()
        except Exception as exc:
            log_exception(__name__, exc)
示例#5
0
    def get_json(url, params):
        '''get info from json api'''
        result = {}
        try:
            response = requests.get(url, data=json.dumps(params), timeout=20)
            if response and response.content and response.status_code == 200:
                result = json.loads(response.content.decode('utf-8', 'replace'))
                if "result" in result:
                    result = result["result"]
            else:
                LOGGER.warning("Invalid or empty reponse from server - server response: %s" %
                        (response.status_code))
        except Exception as exc:
            LOGGER.error("Server is offline or connection error... %s" % exc)

        #log_msg("%s --> %s" %(params, result))
        return result
示例#6
0
 def run(self, host='127.0.0.1', port=5030):
     s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     LOGGER.debug("Listening on udp %s:%s" % (host, port))
     s.bind((host, port))
     while not self._exit.isSet():
         (data, addr) = s.recvfrom(128*1024)
         event = ""
         data = data.decode("utf-8")
         if data.startswith("{"):
             data = json.loads(data)
             if "token" in data:
                 event = "token"
                 data = data["token"]
             elif "metadata" in data:
                 event = "metadata"
                 data = data["metadata"]
         else:
             event = data
         self.callback(event, data)