def init_settings(self):
        """
        Initializes yml-based skill config settings, updating from default dict as necessary for added parameters
        """
        if os.path.isfile(os.path.join(self.root_dir, "settingsmeta.yml")):
            skill_meta = NGIConfig("settingsmeta", self.root_dir).content
        elif os.path.isfile(os.path.join(self.root_dir, "settingsmeta.json")):
            with open(os.path.join(self.root_dir, "settingsmeta.json")) as f:
                skill_meta = json.load(f)
        else:
            skill_meta = None

        # Load defaults from settingsmeta
        default = {"__mycroft_skill_firstrun": True}
        if skill_meta:
            # LOG.info(skill_meta)
            LOG.info(skill_meta["skillMetadata"]["sections"])
            for section in skill_meta["skillMetadata"]["sections"]:
                for pref in section.get("fields", []):
                    if not pref.get("name"):
                        LOG.debug(f"non-data skill meta: {pref}")
                    else:
                        if pref.get("value") == "true":
                            value = True
                        elif pref.get("value") == "false":
                            value = False
                        elif isinstance(pref.get("value"), CommentedMap):
                            value = dict(pref.get("value"))
                        else:
                            value = pref.get("value")
                        default[pref["name"]] = value

        # Load or init configuration
        if os.path.isfile(os.path.join(self.root_dir, f"{self.name}.yml")):
            LOG.warning(
                f"Config found in skill directory for {self.name}! Relocating to: {self.file_system.path}"
            )
            shutil.move(os.path.join(self.root_dir, f"{self.name}.yml"),
                        self.file_system.path)
        self.ngi_settings = NGIConfig(self.name, self.file_system.path)

        # Load any new or updated keys
        try:
            LOG.debug(self.ngi_settings.content)
            LOG.debug(default)
            if self.ngi_settings.content and len(
                    self.ngi_settings.content.keys()) > 0 and len(
                        default.keys()) > 0:
                self.ngi_settings.make_equal_by_keys(default, recursive=False)
            elif len(default.keys()) > 0:
                LOG.info("No settings to load, use default")
                self.ngi_settings.populate(default)
        except Exception as e:
            LOG.error(e)
            self.ngi_settings.populate(default)

        # Make sure settings is initialized as a dictionary
        if self.ngi_settings.content:
            self.settings = self.ngi_settings.content  # Uses the default self.settings object for skills compat
        LOG.debug(f"loaded settings={self.settings}")
    def __init__(self, name=None, bus=None, use_settings=True):
        self.user_config = NGIConfig("ngi_user_info")
        self.local_config = NGIConfig("ngi_local_conf")

        self.ngi_settings: Optional[NGIConfig] = None

        super(NeonSkill, self).__init__(name, bus, use_settings)

        self.cache_loc = os.path.expanduser(
            self.local_config.get('dirVars', {}).get('cacheDir')
            or "~/.local/share/neon/cache")
        self.lru_cache = LRUCache()

        # TODO: Depreciate these references, signal use is discouraged DM
        self.create_signal = create_signal
        self.check_for_signal = check_for_signal

        self.sys_tz = gettz()
        self.gui_enabled = self.configuration_available.get(
            "prefFlags", {}).get("guiEvents", False)

        if use_settings:
            self.settings = {}
            self._initial_settings = None
            self.init_settings()
        else:
            LOG.error(f"{name} Skill requested no settings!")
            self.settings = None

        self.scheduled_repeats = []

        # Server-specific imports and timeout setting
        # A server is a device that hosts the core and skills to serve clients,
        # but that a user will not interact with directly.
        # A server will likely serve multiple users and devices concurrently.
        if self.configuration_available.get("devVars",
                                            {}).get("devType",
                                                    "generic") == "server":
            self.server = True
            self.default_intent_timeout = 90
        else:
            self.server = False
            self.default_intent_timeout = 60

        self.neon_core = True
        self.actions_to_confirm = dict()

        self.skill_mode = self.user_config.content.get('response_mode').get(
            'speed_mode') or DEFAULT_SPEED_MODE
        self.extension_time = SPEED_MODE_EXTENSION_TIME.get(self.skill_mode)

        try:
            # Lang support
            self.language_config = get_neon_lang_config()
            self.lang_detector = DetectorFactory.create()  # Default fastlang
            self.translator = TranslatorFactory.create()  # Default Amazon
        except Exception as e:
            LOG.error(e)
            self.language_config, self.language_detector, self.translator = None, None, None
Example #3
0
    def _init_settings(self):
        """
        Initializes yml-based skill config settings, updating from default dict as necessary for added parameters
        """
        # TODO: This should just use the underlying Mycroft methods DM
        super()._init_settings()
        if os.path.isfile(os.path.join(self.root_dir, "settingsmeta.yml")):
            skill_meta = NGIConfig("settingsmeta", self.root_dir).content
        elif os.path.isfile(os.path.join(self.root_dir, "settingsmeta.json")):
            with open(os.path.join(self.root_dir, "settingsmeta.json")) as f:
                skill_meta = json.load(f)
        else:
            skill_meta = None

        # Load defaults from settingsmeta
        default = {}
        if skill_meta:
            # LOG.info(skill_meta)
            LOG.info(skill_meta["skillMetadata"]["sections"])
            for section in skill_meta["skillMetadata"]["sections"]:
                for pref in section.get("fields", []):
                    if not pref.get("name"):
                        LOG.debug(f"non-data skill meta: {pref}")
                    else:
                        if pref.get("value") == "true":
                            value = True
                        elif pref.get("value") == "false":
                            value = False
                        elif isinstance(pref.get("value"), CommentedMap):
                            value = dict(pref.get("value"))
                        else:
                            value = pref.get("value")
                        default[pref["name"]] = value

        # Load or init configuration
        self._ngi_settings = NGIConfig(self.name, self.settings_write_path)

        # Load any new or updated keys
        try:
            LOG.debug(self._ngi_settings.content)
            LOG.debug(default)
            if self._ngi_settings.content and len(self._ngi_settings.content.keys()) > 0 and len(default.keys()) > 0:
                self._ngi_settings.make_equal_by_keys(default, recursive=False)
            elif len(default.keys()) > 0:
                LOG.info("No settings to load, use default")
                self._ngi_settings.populate(default)
        except Exception as e:
            LOG.error(e)
            self._ngi_settings.populate(default)
Example #4
0
def populate_github_token_config(token: str, config_path: Optional[str] = None):
    """
    Populates configuration with the specified github token for later reference.
    Args:
        token: String Github token
        config_path: Override path to ngi_local_conf
    """
    from neon_utils.configuration_utils import NGIConfig

    assert token

    local_conf = NGIConfig("ngi_local_conf", config_path, True)
    local_conf["skills"]["neon_token"] = token
    local_conf.write_changes()
Example #5
0
def populate_amazon_keys_config(aws_keys: dict, config_path: Optional[str] = None):
    """
    Populates configuration with the specified Amazon keys to be referenced by tts/translation modules.
    Args:
        aws_keys: Dict of aws credentials to use (returned by `find_neon_aws_keys()`)
        config_path: Override path to ngi_local_conf
    """
    from neon_utils.configuration_utils import NGIConfig

    assert "aws_access_key_id" in aws_keys
    assert "aws_secret_access_key" in aws_keys

    if not aws_keys.get("aws_access_key_id") or not aws_keys.get("aws_secret_access_key"):
        raise ValueError

    local_conf = NGIConfig("ngi_local_conf", config_path, True)
    aws_config = local_conf["tts"]["amazon"]
    aws_config = {**aws_config, **aws_keys}
    local_conf["tts"]["amazon"] = aws_config
    local_conf.write_changes()
Example #6
0
 def setUp(self) -> None:
     config_path = os.path.join(ROOT_DIR, "configuration")
     self.old_local_conf = os.path.join(config_path, "old_local_conf.yml")
     self.ngi_local_conf = os.path.join(config_path, "ngi_local_conf.yml")
     shutil.copy(self.ngi_local_conf, self.old_local_conf)
     NGIConfig(self.ngi_local_conf, force_reload=True)