Ejemplo n.º 1
0
    def run(self):
        """
        The main function of the PluginManager.

        Waits on 'self._queue_manager' for event.
        When an event is enqueued, it invokes the according function of the
        PluginBuiltins depending of the nature of the event.
        """
        while self._is_init:
            try:
                event = self._queue_manager.get()
                if event is None:
                    break
                if not event['target']:
                    self._queue_tts.put(
                        'To use a builtin you must specify one argument.')
                    continue
                self._queue_tts.put(
                    getattr(PluginBuiltins, event['action'])(event['target']))
            except:
                import traceback
                self._queue_tts.put(Logger.unexpected_error(self))
                Logger.popup(
                    'Traceback [{0}] {1}: {2}'.format(self.__class__.__name__,
                                                      event['action'],
                                                      event['target']),
                    traceback.format_exc())
            finally:
                self._queue_manager.task_done()
Ejemplo n.º 2
0
    def _load_plugins(self):
        """
        Handler to manage the plugins at the launch of AVA.

        Initialize the folder where the future plugins will be installed.
        Run through this folder and load all the plugins in order to add them
        to the Store and make them available for the whole program.
        """
        targets = []
        if not os.path.exists(self._store.get_path()):
            os.makedirs(self._store.get_path())
            return
        for name in os.listdir(self._store.get_path()):
            if name in ['__pycache__', '__MACOSX', '.DS_Store']:
                continue
            targets.append(name)
        for name in list(set(targets)):
            try:
                self._store.add_plugin(name)
            except:
                import traceback
                print(traceback.format_exc())
                self._queue_tts.put(
                    'Loading of the plugin: {0} failed'.format(name))
                Logger.popup(
                    'Traceback [{0}] Loading of the plugin ({1})'.format(
                        self.__class__.__name__, name), traceback.format_exc())
                continue
Ejemplo n.º 3
0
def wait_for_command(plugin_name: str):
    """
    Wait for an input from the user.

    :param plugin_name: The name of the plugin waiting for an user's input.
    """
    while True:
        execute(plugin_name, input())
        Logger.log_response()
Ejemplo n.º 4
0
def import_module(plugin_name: str):
    """
    Import a module in runtime.

    :param plugin_name: The name of the module to import (string).
    """
    path = os.path.join(os.path.expanduser('~'), '.ava', 'plugins',
                        plugin_name)
    with open(os.path.join(path, 'manifest.json')) as json_file:
        manifest = json.load(json_file)
    assert manifest is not None and 'source' in manifest
    if not PLUGIN[LANG].get(plugin_name):
        if 'build' in manifest and manifest['build'] == True:
            builder(path, plugin_name)
        loader(plugin_name, path, manifest)
    Logger.log_import()
Ejemplo n.º 5
0
    def run(self):
        """
        The main function of the PluginListener.

        Designed as an infinite loop, The PluginListener is constantly listening
        the plugins installed in order to process the result of their execution
        and perform a feedback to the user.
        """
        while self._is_init:
            try:
                self._listener.listen()
            except:
                import traceback
                self._queues['QueueTextToSpeech'].put(
                    Logger.unexpected_error(self))
                Logger.popup('Traceback [{0}]'.format(self.__class__.__name__),
                             traceback.format_exc())
Ejemplo n.º 6
0
    def _process_result(self, plugin_name: str, process: subprocess.Popen):
        """
        This function is called when an event has been detected on the stdout
        file descriptor of a plugin's process.
        It flushes the data print on the stdout of the process and processes it.
        A message is enqueued in 'self._queue_tts' which is the queue dedicated
        to the text-to-speech component. It allows us to perform a feedback to
        the user about the command which he/she has just dictated.

        :param plugin_name: The name of the plugin (string).
        :param process: The instance of the subprocess.Popen object of a plugin
         (subprocess.Popen).
        """
        output, import_flushed = flush_stdout(process)
        if Logger.ERROR in output:
            output.remove(Logger.ERROR)
            self._queue_tts.put(
                'Plugin {} just crashed... Restarting'.format(plugin_name))
            Logger.popup(
                'Traceback - Plugin [{0}] previous command FAILED'.format(
                    plugin_name), output)
            plugin = self._store.get_plugin(plugin_name)
            if plugin is not None and isinstance(plugin, Plugin):
                plugin.kill()
                plugin.restart()
            return
        elif Logger.IMPORT in output:
            return
        elif Logger.REQUEST in output:
            output.remove(Logger.REQUEST)
            self._state.plugin_requires_user_interaction(plugin_name)
            self._queue_tts.put(ast.literal_eval(''.join(output)).get('tts'))
            return
        else:
            output.remove(Logger.RESPONSE)
            result, multi_lines = multi_lines_output_handler(output)
            if multi_lines:
                self._queue_tts.put(
                    'Result of [{}] has been print.'.format(plugin_name))
                Logger.popup(plugin_name, result)
                return
            self._queue_tts.put(result)
Ejemplo n.º 7
0
        if LANG == 'cpp':
            if plugin.get(command_name):
                print(plugin[command_name](args if args else ''))
                return
        elif LANG == 'go':
            func = getattr(plugin, command_name, None)
            if func is not None:
                func(args if args else '')
                return
        else:
            if command_name in plugin.__dict__:
                plugin.__dict__[command_name](plugin, args if args else None)
                return
        print('The plugin {} cannot handle the following command: {}'.format(
            plugin_name, command_name),
              flush=False)
    else:
        raise RuntimeError('Unexpected error occured.')


if __name__ == "__main__":
    try:
        plugin_name = sys.argv[1]
        LANG = sys.argv[2]
        import_module(plugin_name)
        wait_for_command(plugin_name)
    except:
        import traceback
        traceback.print_exc(file=sys.stdout)
        Logger.log_error()