Ejemplo n.º 1
0
 def manage(self,
            name,
            action,
            author_email=None,
            author_name=None,
            dev_mode=False):
     if action == "install":
         status = PluginManager.installPlugin(plugin_name=name,
                                              dev_mode=dev_mode)
     elif action == "disable":
         status = PluginManager.disablePlugin(plugin_name=name)
     elif action == "uninstall":
         status = PluginManager.uninstallPlugin(plugin_name=name,
                                                dev_mode=dev_mode)
     elif action == "enable":
         status = PluginManager.enablePlugin(plugin_name=name)
     elif action == "create":
         status = PluginManager.createPlugin(plugin_name=name,
                                             author_name=author_name,
                                             author_email=author_email)
     else:
         exit()
     if status['status'] == 'success':
         self.stdout.write("[" + self.OKGREEN + "OK" + self.ENDC + "]" +
                           " " + status['log'])
     else:
         self.stdout.write("[" + self.FAIL + "FAIL" + self.ENDC + "]" +
                           " " + status['log'])
Ejemplo n.º 2
0
    def list_plugins(self, jsonInput):
        # Get context
        context = jsonInput['context']

        # Parse plugins that has i_can strings
        desc_list = []
        for plugin in PluginManager.getEnabledPlugins():
            if hasattr(plugin, 'i_can') == True and plugin.i_can is not None:
                # Get translation method from plugin
                instance = PluginManager.getPluginInstance(plugin.name)

                # Translate intent description
                desc_list.append(instance._(plugin.i_can))

        # When there is too much sentences
        message = ""
        if len(desc_list) > 4:
            message = self._("i_can_do_many") + ". "

        # Get 4 sentences randomly
        for i in range(4):
            if len(desc_list) == 0:
                break

            val = int(random() * len(desc_list))
            message += desc_list[val] + ". "
            desc_list.pop(val)

        # Speak to client
        self.speakToClient(text=message, context=context)
Ejemplo n.º 3
0
    def list_plugins(self, jsonInput):
        # Get context
        context = jsonInput['context']

        # Parse plugins that has i_can strings
        desc_list = []
        for plugin in PluginManager.getEnabledPlugins():
            if hasattr(plugin, 'i_can') == True and plugin.i_can is not None:
                # Get translation method from plugin
                instance = PluginManager.getPluginInstance(plugin.name)

                # Translate intent description
                desc_list.append(instance._(plugin.i_can))

        # When there is too much sentences
        message = ""
        if len(desc_list) > 4:
            message = self._("i_can_do_many") + ". "

        # Get 4 sentences randomly
        for i in range(4):
            if len(desc_list) == 0:
                break;

            val = int(random() * len(desc_list))
            message += desc_list[val] + ". "
            desc_list.pop(val)

        # Speak to client
        self.speakToClient(text = message, context = context)
Ejemplo n.º 4
0
    def __init__(self, client_uid):
        # Client context
        self.client = NeoContext.__factory.getClient(client_uid)
        self.wait_step = None
        self._client_steps = {'count': 0, 'first': None, 'last': None}
        self.Vars = {}

        # Init plugins client variables
        PluginManager.initContext(context=self)
Ejemplo n.º 5
0
    def methodslist(self, request, **kwargs):
        self.method_check(request, allowed=['get'])
        self.is_authenticated(request)
        self.throttle_check(request)

        if 'plugin_name' in kwargs:
            methods = PluginManager.getPluginMethods(plugin_name = kwargs['plugin_name'])
        else:
            methods = PluginManager.getPluginMethods()
        self.log_throttled_access(request)
        return self.create_response(request, methods, HttpAccepted)
Ejemplo n.º 6
0
    def list_plugin_intents(self, jsonInput):
        # Get context
        context = jsonInput['context']

        # Get plugin name
        plugin_name = None
        try:
            plugin_name = jsonInput['outcome']['entities']['plugin_name'][
                'value']
        except:
            pass

        # Parse intents that has i_can strings
        desc_list = []
        for intent in PluginManager.getEnabledIntents():
            if NeoConv.compareSimilar(intent.plugin_name,
                                      plugin_name) == False:
                continue

            if hasattr(intent, 'i_can') == True and intent.i_can is not None:
                # Get translation method from plugin
                instance = PluginManager.getPluginInstance(intent.plugin_name)

                # Translate intent description
                desc_list.append(instance._(intent.i_can))

        # If no plugin given
        if len(desc_list) == 0:
            # No plugin
            message = self._("core_intent_no_plugin")

            # Speak to client
            self.speakToClient(text=message, context=context)

            return

        # When there is too much sentences
        message = ""
        if len(desc_list) > 4:
            message = self._("i_can_do_many") + ". "

        # Get 4 sentences randomly
        for i in range(4):
            if len(desc_list) == 0:
                break

            val = int(random() * len(desc_list))
            message += desc_list[val] + ". "
            desc_list.pop(val)

        # Speak to client
        self.speakToClient(text=message, context=context)
Ejemplo n.º 7
0
    def list_plugin_intents(self, jsonInput):
        # Get context
        context = jsonInput['context']

        # Get plugin name
        plugin_name = None
        try:
            plugin_name = jsonInput['outcome']['entities']['plugin_name']['value']
        except:
            pass

        # Parse intents that has i_can strings
        desc_list = []
        for intent in PluginManager.getEnabledIntents():
            if NeoConv.compareSimilar(intent.plugin_name, plugin_name) == False:
                continue

            if hasattr(intent, 'i_can') == True and intent.i_can is not None:
                # Get translation method from plugin
                instance = PluginManager.getPluginInstance(intent.plugin_name)

                # Translate intent description
                desc_list.append(instance._(intent.i_can))

        # If no plugin given
        if len(desc_list) == 0:
            # No plugin
            message = self._("core_intent_no_plugin")

            # Speak to client
            self.speakToClient(text = message, context = context)

            return

        # When there is too much sentences
        message = ""
        if len(desc_list) > 4:
            message = self._("i_can_do_many") + ". "

        # Get 4 sentences randomly
        for i in range(4):
            if len(desc_list) == 0:
                break;

            val = int(random() * len(desc_list))
            message += desc_list[val] + ". "
            desc_list.pop(val)

        # Speak to client
        self.speakToClient(text = message, context = context)
Ejemplo n.º 8
0
    def __init__(self, plugin_name = None):
        """
        Set the basic variables.
        """
        # UID will be set by PluginManager just after constructor
        self.uid = None

        # Server configuration
        self.configuration_server = ConfigManager.getConfiguration()

        # New-style plugins give their name to initiate services
        if plugin_name is not None:
            # Read configuration
            self.plugin = PluginManager.getPlugin(plugin_name = plugin_name)
            self.configuration_plugin = self.plugin.configuration

            # Init translation function
            lang_path = self.plugin.path + '/lang'
            self._ = NeoTrans(domain = plugin_name.lower(), localedir = lang_path, fallback = True, languages = [self.configuration_server['lang_short']]).Trans
        # Old-style plugins
        else:
            # Open database
            self.mongo = MongoClient(host = self.configuration_server['database']['server'], port = self.configuration_server['database']['port'])
            self.configuration_lisa = self.configuration_server
            self.configuration_lisa['lang'] = self.configuration_lisa['lang_short']
Ejemplo n.º 9
0
    def parseChat(cls, jsonData, client_uid):
        # Create singleton
        if cls.__instance is None:
            cls.__instance = ClientFactory()
        self = cls.__instance

        # If input has already a decoded intent
        if jsonData.has_key("outcome") == True:
            jsonInput = {}
            jsonInput['outcome'] = jsonData['outcome']
        elif len(jsonData['body']) > 0:
            # Ask Wit for intent decoding
            jsonInput = self.wit.get_message(unicode(jsonData['body']))
        else:
            # No input => no output
            return

        # Initialize output from input
        jsonInput['from'], jsonInput['type'], jsonInput['zone'] = jsonData['from'], jsonData['type'], jsonData['zone']

        # Show wit result
        if configuration['debug']['debug_wit']:
            log.msg("WIT: " + str(jsonInput['outcome']))

        # Execute intent
        client = cls.getClient(client_uid)
        intent = PluginManager.getIntent(intent_name = jsonInput['outcome']['intent'])
        if intent is not None:
            # Call plugin
            client['context'].parse(jsonInput = jsonInput, plugin_name = intent.plugin_name, method_name = intent.method_name)
        else:
            # Parse without intent
            client['context'].parse(jsonInput = jsonInput)
Ejemplo n.º 10
0
    def __init__(self, plugin_name=None):
        """
        Set the basic variables.
        """
        # UID will be set by PluginManager just after constructor
        self.uid = None

        # Server configuration
        self.configuration_server = ConfigManager.getConfiguration()

        # New-style plugins give their name to initiate services
        if plugin_name is not None:
            # Read configuration
            self.plugin = PluginManager.getPlugin(plugin_name=plugin_name)
            self.configuration_plugin = self.plugin.configuration

            # Init translation function
            lang_path = self.plugin.path + '/lang'
            self._ = NeoTrans(
                domain=plugin_name.lower(),
                localedir=lang_path,
                fallback=True,
                languages=[self.configuration_server['lang_short']]).Trans
        # Old-style plugins
        else:
            # Open database
            self.mongo = MongoClient(
                host=self.configuration_server['database']['server'],
                port=self.configuration_server['database']['port'])
            self.configuration_lisa = self.configuration_server
            self.configuration_lisa['lang'] = self.configuration_lisa[
                'lang_short']
Ejemplo n.º 11
0
    def deinit(cls):
        # Lock access
        cls.__lock.acquire()

        # Clean global vars
        cls.__global_ctx = None
        cls.__history = None
        cls.__steps = None
        cls.__Vars = None
        cls._ = None
        cls.__factory = None

        # Deinit plugin manager
        PluginManager.deinit()

        # Release access
        cls.__lock.release()
Ejemplo n.º 12
0
 def manage(self, name, action, author_email=None, author_name=None, dev_mode=False):
     if action == "install":
         status = PluginManager.installPlugin(plugin_name=name, dev_mode=dev_mode)
     elif action == "disable":
         status = PluginManager.disablePlugin(plugin_name=name)
     elif action == "uninstall":
         status = PluginManager.uninstallPlugin(plugin_name=name, dev_mode=dev_mode)
     elif action == "enable":
         status = PluginManager.enablePlugin(plugin_name=name)
     elif action == "create":
         status = PluginManager.createPlugin(plugin_name=name, author_name=author_name, author_email=author_email)
     else:
         exit()
     if status['status'] == 'success':
         self.stdout.write("[" + self.OKGREEN + "OK" + self.ENDC + "]" + " " + status['log'])
     else:
         self.stdout.write("[" + self.FAIL + "FAIL" + self.ENDC + "]" + " " + status['log'])
Ejemplo n.º 13
0
    def enable(self, request, **kwargs):
        self.method_check(request, allowed=['get'])
        self.is_authenticated(request)
        self.throttle_check(request)

        status = PluginManager.enablePlugin(plugin_pk=kwargs['pk'])
        self.log_throttled_access(request)
        ClientFactory.SchedReload()
        ClientFactory.LisaReload()
        return self.create_response(request, status, HttpAccepted)
Ejemplo n.º 14
0
    def install(self, request, **kwargs):
        self.method_check(request, allowed=['post','get'])
        self.is_authenticated(request)
        self.throttle_check(request)
        plugin_name = kwargs['plugin_name']
        status = PluginManager.installPlugin(plugin_name=plugin_name)

        self.log_throttled_access(request)
        ClientFactory.SchedReload()
        ClientFactory.LisaReload()
        return self.create_response(request, status, HttpCreated)
Ejemplo n.º 15
0
    def parseChat(cls, jsonData, client_uid):
        # Create singleton
        if cls.__instance is None:
            cls.__instance = ClientFactory()
        self = cls.__instance

        # If input has already a decoded intent
        if jsonData.has_key("outcome") == True:
            jsonInput = {}
            jsonInput['outcome'] = jsonData['outcome']
        elif len(jsonData['body']) > 0:
            # Ask Wit for intent decoding
            jsonInput = self.wit.get_message(unicode(jsonData['body']))
        else:
            # No input => no output
            return

        # Initialize output from input
        jsonInput['from'], jsonInput['type'], jsonInput['zone'] = jsonData[
            'from'], jsonData['type'], jsonData['zone']

        # Show wit result
        if configuration['debug']['debug_wit']:
            log.msg("WIT: " + str(jsonInput['outcome']))

        # Execute intent
        client = cls.getClient(client_uid)
        intent = PluginManager.getIntent(
            intent_name=jsonInput['outcome']['intent'])
        if intent is not None:
            # Call plugin
            client['context'].parse(jsonInput=jsonInput,
                                    plugin_name=intent.plugin_name,
                                    method_name=intent.method_name)
        else:
            # Parse without intent
            client['context'].parse(jsonInput=jsonInput)
Ejemplo n.º 16
0
 def test_a_install_plugin_ok(self):
     answer = PluginManager.installPlugin(plugin_name="UnitTest", test_mode=True)
     self.assertEqual(answer['status'], "success")
Ejemplo n.º 17
0
 def test_gg_uninstall_plugin(self):
     answer = PluginManager.uninstallPlugin(plugin_name="UnitTest")
     self.assertEqual(answer['status'], "fail")
Ejemplo n.º 18
0
 def test_f_create_plugin(self):
     os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lisa.server.web.weblisa.settings")
     answer = PluginManager.createPlugin(plugin_name="TestPlugin", author_name="TestAuthor",
                                              author_email="*****@*****.**")
     self.assertEqual(answer['status'], "success")
Ejemplo n.º 19
0
 def test_e_methodList_plugin(self):
     answer = PluginManager.getPluginMethods()
     methodlist = [{'methods': ['test'], 'plugin': u'UnitTest'}, {'core': 'intents', 'methods': ['list']}]
     self.assertListEqual(answer, methodlist)
Ejemplo n.º 20
0
 def test_d_load_plugin(self):
     answer = PluginManager.getEnabledPluginNames()
     test_list = ['UnitTest']
     self.assertListEqual(answer, test_list)
Ejemplo n.º 21
0
 def test_cc_enable_plugin_fail(self):
     answer = PluginManager.enablePlugin(plugin_name="UnitTest")
     self.assertEqual(answer['status'], "fail")
Ejemplo n.º 22
0
    def _create_step(cls, plugin_uid=None, context=None):
        # Lock access
        NeoContext.__lock.acquire()

        # Create a step
        step_uid = str(uuid.uuid1())
        step = {
            'uid': step_uid,
            'date': datetime.now(),
            'previous': None,
            'next': None,
            'client_uid': None,
            'client_previous': None,
            'client_next': None,
            'plugin_uid': plugin_uid,
            'plugin_previous': None,
            'plugin_next': None
        }
        cls.__history[step_uid] = step

        # First step
        cls.__steps['count'] += 1
        if cls.__steps['first'] is None:
            cls.__steps['first'] = step_uid

        # Link to last step
        if cls.__steps['last'] is not None:
            cls.__history[cls.__steps['last']]['next'] = step_uid
            step['previous'] = cls.__history[cls.__steps['last']]['uid']
        cls.__steps['last'] = step_uid

        # link to a client
        if context is not None:
            # Set client uid
            step['client_uid'] = context.client['uid']

            # First client step
            context._client_steps['count'] += 1
            if context._client_steps['first'] is None:
                context._client_steps['first'] = step_uid

            # Link to client last step
            if context._client_steps['last'] is not None:
                cls.__history[
                    context._client_steps['last']]['client_next'] = step_uid
                step['client_previous'] = cls.__history[
                    context._client_steps['last']]['uid']
            context._client_steps['last'] = step_uid

        # link to a plugin
        if plugin_uid is not None:
            # First plugin step
            plugin = PluginManager.getPlugin(plugin_uid=plugin_uid)
            plugin.steps['count'] += 1
            if plugin.steps['first'] is None:
                plugin.steps['first'] = step_uid

            # Link to plugin last step
            if plugin.steps['last'] is not None:
                cls.__history[plugin.steps['last']]['plugin_next'] = step_uid
                step['plugin_previous'] = cls.__history[
                    plugin.steps['last']]['uid']
            plugin.steps['last'] = step_uid

        # Release access
        cls.__lock.release()

        return step
Ejemplo n.º 23
0
Archivo: urls.py Proyecto: gdumee/LISA
v1_api.register(IntentResource())
v1_api.register(WorkspaceResource())
v1_api.register(WidgetResource())
v1_api.register(WidgetByUserResource())
v1_api.register(LisaResource())

urlpatterns = patterns(
    '',
    url(r'^speech/', include('lisa.server.web.googlespeech.urls')),
    url(r'^plugins/', include('lisa.server.web.manageplugins.urls')),
    url(r'', include('lisa.server.web.interface.urls')),
)

#Register plugin's API
from lisa.server.plugins.PluginManager import PluginManager
for plugin in PluginManager.getEnabledPluginNames():
    urlpatterns += patterns(
        '',
        url(r'^' + str(plugin) + r'/',
            include('lisa.plugins.' + str(plugin) + '.web.urls')))
    v1_api.register(
        namedAny('lisa.plugins.' + plugin + '.web.api.' + plugin +
                 'Resource')())

urlpatterns += patterns(
    '',
    url(r'^api/', include(v1_api.urls)),
    url(r'^api/docs/',
        include('tastypie_swagger.urls', namespace='tastypie_swagger')),
)
Ejemplo n.º 24
0
    def parse(self, jsonInput, plugin_name=None, method_name=None):
        # If waiting an answer
        if self._process_answer(jsonInput) == True:
            # The answer was processed
            return

        # Check Wit confidence
        if jsonInput['outcome'].has_key(
                'confidence') == False or jsonInput['outcome'][
                    'confidence'] < configuration_server['wit_confidence']:
            # Add an error step
            step = NeoContext._create_step(context=self)
            step['type'] = "error confidence"
            step['in_json'] = jsonInput.copy()

            # Return an error to client
            jsonData = {
                'type': 'Error',
                'message': _("error_intent_low_confidence")
            }
            NeoContext.__factory.sendToClients(
                client_uids=[self.client['uid']], jsonData=jsonData)
            return

        # Get initialized plugin
        plugin = PluginManager.getPlugin(plugin_name=plugin_name)
        if plugin is None:
            # Add an error step
            step = NeoContext._create_step(context=self)
            step['type'] = "Error no plugin"
            step['in_json'] = jsonInput.copy()

            # Return an error to client
            jsonData = {'type': 'Error', 'message': _("error_intent_unknown")}
            NeoContext.__factory.sendToClients(
                client_uids=[self.client['uid']], jsonData=jsonData)
            return

        # Get method to call
        methodToCall = PluginManager.getPluginMethod(plugin=plugin,
                                                     method_name=method_name)
        if methodToCall is None:
            # Add an error step
            step = NeoContext._create_step(plugin_uid=plugin.uid, context=self)
            step['type'] = "Error plugin no method"
            step['plugin_name'] = plugin_name
            step['method_name'] = method_name
            step['in_json'] = jsonInput.copy()

            # Return an error to client
            jsonData = {'type': 'Error', 'message': _("error_plugin_no_func")}
            NeoContext.__factory.sendToClients(
                client_uids=[self.client['uid']], jsonData=jsonData)
            return

        # Save step in context
        step = NeoContext._create_step(plugin_uid=plugin.uid, context=self)
        step['type'] = "Plugin call"
        step['in_json'] = jsonInput.copy()

        # Call plugin method
        jsonInput['context'] = self
        try:
            jsonOutput = methodToCall(jsonInput)
        except:
            # In debug mode, raise exception
            if configuration_server['debug']['debug_plugin'] == True:
                raise

            # Add an error step
            step = NeoContext._create_step(context=self)
            step['type'] = "error plugin exec"
            step['plugin_name'] = plugin_name
            step['method_name'] = method_name
            step['in_json'] = jsonInput.copy()

            # Return an error to client
            jsonData = {'type': 'Error', 'message': _("error_plugin_exec")}
            NeoContext.__factory.sendToClients(
                client_uids=[self.client['uid']], jsonData=jsonData)
            return

        # Old-style plugin output
        if jsonOutput is not None:
            self.speakToClient(plugin_uid=plugin.uid, text=jsonOutput['body'])
Ejemplo n.º 25
0
 def test_c_enable_plugin_ok(self):
     answer = PluginManager.enablePlugin(plugin_name="UnitTest")
     self.assertEqual(answer['status'], "success")
Ejemplo n.º 26
0
    def init(cls, factory):
        # Set factory
        cls.__factory = factory

        # Init plugin manager
        PluginManager.init(global_context=cls)
Ejemplo n.º 27
0
Archivo: urls.py Proyecto: gdumee/LISA
from api import LisaResource, UserResource
from twisted.python.reflect import namedAny
import tastypie_swagger

v1_api = Api(api_name='v1')
v1_api.register(UserResource())
v1_api.register(PluginResource())
v1_api.register(IntentResource())
v1_api.register(WorkspaceResource())
v1_api.register(WidgetResource())
v1_api.register(WidgetByUserResource())
v1_api.register(LisaResource())

urlpatterns = patterns('',
    url(r'^speech/', include('lisa.server.web.googlespeech.urls')),
    url(r'^plugins/', include('lisa.server.web.manageplugins.urls')),
    url(r'', include('lisa.server.web.interface.urls')),
)

#Register plugin's API
from lisa.server.plugins.PluginManager import PluginManager
for plugin in PluginManager.getEnabledPluginNames():
    urlpatterns += patterns('', url(r'^' + str(plugin) + r'/', include('lisa.plugins.' +
                                                                       str(plugin) + '.web.urls')))
    v1_api.register(namedAny('lisa.plugins.' + plugin + '.web.api.' + plugin + 'Resource')())

urlpatterns += patterns('',
    url(r'^api/', include(v1_api.urls)),
    url(r'^api/docs/', include('tastypie_swagger.urls', namespace='tastypie_swagger')),
)