Esempio n. 1
0
    def filter(self, level=None, limit=None):
        """
        Filters to apply to logs for output.
        """

        if not level:
            level = self.logger.levelno

        elif isint(level):
            levels = sorted_levels("number")

            if level in list(levels.keys()):
                level = int(level)

            else:
                level = closest_int_from_list(list(levels.keys()), int(level))

        else:

            levels = sorted_levels("name")
            if level not in levels:
                level = self.logger.levelname

            level = logging.getLevelName(level.upper())

        if limit and not isint(limit):
            limit = None

        filterdict = {}
        for log_entry in list(self.dict.keys()):

            if self.dict[log_entry]["levelno"] >= level:
                filterdict[log_entry] = self.dict[log_entry]

        if limit:
            limit_entries = list(filterdict.keys())[-int(limit):]
            limitdict = {}

            for entry_item in limit_entries:
                limitdict[entry_item] = filterdict[entry_item]

            returndict = limitdict

        else:

            returndict = filterdict

        return returndict
Esempio n. 2
0
    def get_channels(self):

        stations_url = 'https://api.locastnet.org/api/watch/epg/%s' % self.location[
            "DMA"]
        url_headers = {
            'Content-Type': 'application/json',
            'authorization': 'Bearer %s' % self.token
        }

        try:
            stationsReq = self.plugin_utils.web.session.get(
                stations_url, headers=url_headers)
            stationsReq.raise_for_status()
        except self.plugin_utils.web.exceptions.SSLError as err:
            self.plugin_utils.logger.error('Error while getting stations: %s' %
                                           err)
            return []
        except self.plugin_utils.web.exceptions.HTTPError as err:
            self.plugin_utils.logger.error('Error while getting stations: %s' %
                                           err)
            return []

        stationsRes = stationsReq.json()

        cleaned_channels = []
        for station_item in stationsRes:

            thumbnails = []
            for thumb_opt in ["logo226Url", "logoUrl"]:

                try:
                    thumbnail = station_item[thumb_opt]
                except TypeError:
                    thumbnail = None
                except KeyError:
                    thumbnail = None
                if thumbnail:
                    thumbnails.append(thumbnail)
            if not len(thumbnails):
                thumbnails = [None]

            clean_station_item = {
                "name": station_item["name"],
                "id": station_item["id"],
                "thumbnail": thumbnails[0]
            }

            # Typically this will be `2.1 KTTW` but occasionally Locast only provides a channel number here
            # fHDHR device.channels will provide us a number if that is the case
            if (isint(str(station_item['callSign']).split(" ")[0])
                    or isfloat(str(station_item['callSign']).split(" ")[0])):
                clean_station_item["number"] = str(
                    station_item['callSign']).split(" ")[0]
                clean_station_item["callsign"] = str(" ".join(
                    station_item['callSign'].split(" ")[1:]))
            else:
                clean_station_item["callsign"] = str(station_item['callSign'])

            cleaned_channels.append(clean_station_item)
        return cleaned_channels
Esempio n. 3
0
    def write(self, key, value, section):

        if not value:
            value = None
        elif key == "xmltv_offset":
            value = str(value)
        elif str(value) in ["0"]:
            value = 0
        elif isint(value):
            value = int(value)
        elif isfloat(value):
            value = float(value)
        elif is_arithmetic(value):
            value = eval(value)
        elif isinstance(value, list):
            ",".join(value)
        elif str(value).lower() in ["none", ""]:
            value = None
        elif str(value).lower() in ["false"]:
            value = False
        elif str(value).lower() in ["true"]:
            value = True

        self.dict[section][key] = value

        config_handler = configparser.ConfigParser()
        config_handler.read(self.config_file)

        if not config_handler.has_section(section):
            config_handler.add_section(section)

        config_handler.set(section, key, str(value))

        with open(self.config_file, 'w') as config_file:
            config_handler.write(config_file)
Esempio n. 4
0
    def levelname(self):
        """
        Convert a configuration level name/number to applicable name.
        """

        if isint(self.config.dict["logging"]["level"]):

            levels = sorted_levels("number")

            if self.config.dict["logging"]["level"] in list(levels.keys()):
                level = int(self.config.dict["logging"]["level"])

            else:
                level = closest_int_from_list(list(levels.keys()), int(self.config.dict["logging"]["level"]))

            return logging.getLevelName(level)
        else:

            levels = sorted_levels("name")
            level = self.config.dict["logging"]["level"].upper()

            if self.config.dict["logging"]["level"].upper() not in levels:
                level = self.config.conf_default["logging"]["level"]["value"]

            return level
Esempio n. 5
0
    def write(self, section, key, value):

        if not value:
            value = None
        if value.lower() in ["none"]:
            value = None
        elif value.lower() in ["false"]:
            value = False
        elif value.lower() in ["true"]:
            value = True
        elif isint(value):
            value = int(value)
        elif isfloat(value):
            value = float(value)
        elif isinstance(value, list):
            ",".join(value)

        if section == self.dict["main"]["dictpopname"]:
            self.dict["origin"][key] = value
        else:
            self.dict[section][key] = value

        config_handler = configparser.ConfigParser()
        config_handler.read(self.config_file)

        if not config_handler.has_section(section):
            config_handler.add_section(section)

        config_handler.set(section, key, str(value))

        with open(self.config_file, 'w') as config_file:
            config_handler.write(config_file)
Esempio n. 6
0
    def read_json_config(self, conffilepath):
        with open(conffilepath, 'r') as jsonconf:
            confimport = json.load(jsonconf)
        for section in list(confimport.keys()):

            if section not in self.dict.keys():
                self.dict[section] = {}

            if section not in self.conf_default.keys():
                self.conf_default[section] = {}

            for key in list(confimport[section].keys()):

                if key not in list(self.conf_default[section].keys()):
                    self.conf_default[section][key] = {}

                confvalue = confimport[section][key]["value"]
                if key == "xmltv_offset":
                    confvalue = str(confvalue)
                elif isint(confvalue):
                    confvalue = int(confvalue)
                elif isfloat(confvalue):
                    confvalue = float(confvalue)
                elif is_arithmetic(confvalue):
                    confvalue = eval(confvalue)
                elif "," in confvalue:
                    confvalue = confvalue.split(",")
                elif str(confvalue).lower() in ["none"]:
                    confvalue = None
                elif str(confvalue).lower() in ["false"]:
                    confvalue = False
                elif str(confvalue).lower() in ["true"]:
                    confvalue = True

                self.dict[section][key] = confvalue

                self.conf_default[section][key]["value"] = confvalue

                for config_option in [
                        "config_web_hidden", "config_file", "config_web"
                ]:
                    if config_option not in list(
                            confimport[section][key].keys()):
                        config_option_value = False
                    else:
                        config_option_value = confimport[section][key][
                            config_option]
                        if str(config_option_value).lower() in ["none"]:
                            config_option_value = None
                        elif str(config_option_value).lower() in ["false"]:
                            config_option_value = False
                        elif str(config_option_value).lower() in ["true"]:
                            config_option_value = True
                    self.conf_default[section][key][
                        config_option] = config_option_value
Esempio n. 7
0
    def channel_number_convert(self, channel):

        if channel.startswith("v"):
            channel_number = channel.replace('v', '')
            if not isint(channel_number) and not isfloat(channel_number):
                return None, ("Invalid Channel %s" % channel)
            return channel_number, None

        elif channel.startswith("ch"):
            channel_freq = channel.replace('ch', '').split("-")[0]
            subchannel = None
            if "-" in channel:
                subchannel = channel.replace('ch', '').split("-")[1]
            return None, ("Not Implemented %s-%s" % (channel_freq, subchannel))

        else:
            return None, ("Invalid Channel %s" % channel)
Esempio n. 8
0
    def get_real_conf_value(self, key, confvalue):
        """
        Check config value is prepped correctly.
        """

        if not confvalue:
            confvalue = None

        elif isinstance(confvalue, type(None)):
            confvalue = None

        elif key == "xmltv_offset":
            confvalue = str(confvalue)

        elif str(confvalue) in [0, "0"]:
            confvalue = 0

        elif isint(confvalue):
            confvalue = int(confvalue)

        elif isfloat(confvalue):
            confvalue = float(confvalue)

        elif is_arithmetic(confvalue):
            confvalue = eval(confvalue)

        elif "," in confvalue:
            confvalue = confvalue.split(",")

        elif str(confvalue).lower() in ["none", ""]:
            confvalue = None

        elif str(confvalue).lower() in ["false"]:
            confvalue = False

        elif str(confvalue).lower() in ["true"]:
            confvalue = True

        return confvalue
Esempio n. 9
0
 def get_real_conf_value(self, key, confvalue):
     if not confvalue:
         confvalue = None
     elif key == "xmltv_offset":
         confvalue = str(confvalue)
     elif str(confvalue) in ["0"]:
         confvalue = 0
     elif isint(confvalue):
         confvalue = int(confvalue)
     elif isfloat(confvalue):
         confvalue = float(confvalue)
     elif is_arithmetic(confvalue):
         confvalue = eval(confvalue)
     elif "," in confvalue:
         confvalue = confvalue.split(",")
     elif str(confvalue).lower() in ["none", ""]:
         confvalue = None
     elif str(confvalue).lower() in ["false"]:
         confvalue = False
     elif str(confvalue).lower() in ["true"]:
         confvalue = True
     return confvalue
Esempio n. 10
0
    def get_levelno(self, level):
        """
        Convert a level name/number to applicable number.
        """

        if isint(level):

            levels = sorted_levels("number")

            if level in list(levels.keys()):
                return int(level)

            else:
                return closest_int_from_list(list(levels.keys()), int(level))

        else:

            levels = sorted_levels("name")
            if level not in levels:
                level = self.levelname

            return logging.getLevelName(level.upper())
Esempio n. 11
0
 def read_config(self, conffilepath):
     config_handler = configparser.ConfigParser()
     config_handler.read(conffilepath)
     for each_section in config_handler.sections():
         if each_section.lower() not in list(self.dict.keys()):
             self.dict[each_section.lower()] = {}
         for (each_key, each_val) in config_handler.items(each_section):
             if not each_val:
                 each_val = None
             elif each_val.lower() in ["none", "false"]:
                 each_val = False
             elif each_val.lower() in ["true"]:
                 each_val = True
             elif isint(each_val):
                 each_val = int(each_val)
             elif isfloat(each_val):
                 each_val = float(each_val)
             elif is_arithmetic(each_val):
                 each_val = eval(each_val)
             elif "," in each_val:
                 each_val = each_val.split(",")
             self.dict[each_section.lower()][each_key.lower()] = each_val
Esempio n. 12
0
    def read_ini_config(self, conffilepath):
        config_handler = configparser.ConfigParser()
        config_handler.read(conffilepath)
        for each_section in config_handler.sections():
            if each_section.lower() not in list(self.dict.keys()):
                self.dict[each_section.lower()] = {}
            for (each_key, each_val) in config_handler.items(each_section):
                if not each_val:
                    each_val = None
                elif each_key == "xmltv_offset":
                    each_val = str(each_val)
                elif each_val.lower() in ["none"]:
                    each_val = None
                elif each_val.lower() in ["false"]:
                    each_val = False
                elif each_val.lower() in ["true"]:
                    each_val = True
                elif isint(each_val):
                    each_val = int(each_val)
                elif isfloat(each_val):
                    each_val = float(each_val)
                elif is_arithmetic(each_val):
                    each_val = eval(each_val)
                elif "," in each_val:
                    each_val = each_val.split(",")

                import_val = True
                if each_section in list(self.conf_default.keys()):
                    if each_key in list(
                            self.conf_default[each_section].keys()):
                        if not self.conf_default[each_section][each_key][
                                "config_file"]:
                            import_val = False

                if import_val:
                    self.dict[each_section.lower()][
                        each_key.lower()] = each_val