Example #1
0
    def load(cls):
        """
        Load YML signals file
        """

        cls._signals = []

        signals_file = cls._get_signals_file()
        try:
            signals = yaml.load(open(signals_file, 'r'))
            Log.info("Loading signals information from " + signals_file)
        except:
            Log.error("Loading signals information failed from " +
                      signals_file)
            return

        if signals is not None:
            for device_code, device_info in signals.items():
                for sub_code, sub_info in device_info['subs'].items():
                    signal = Signal(
                        manager=App.components.get(sub_info['manager']),
                        code=sub_info['code'],
                        dump=sub_info['dump'],
                        device_code=device_code,
                        device_name=device_info['name'],
                        sub_code=sub_code,
                        sub_name=sub_info['name'],
                    )

                    cls._signals.append(signal)
Example #2
0
    def send_message(self, text, recipients=None):
        if recipients is None:
            recipients = self._allowed_users

        for recipient in recipients:
            chat_id = self.get_chat_id(recipient)
            if chat_id is not None:
                self.get_bot().sendMessage(chat_id, text)
            else:
                Log.error('Unknown chat ID for user ' + recipient +
                          ', please send a message to this bot')
Example #3
0
    def _load_runtime(self):
        self._chat_ids = {}

        runtime_file = self._get_runtime_file()
        try:
            runtime = yaml.load(open(runtime_file, 'r'))
            Log.info("Loading runtime from " + runtime_file)
        except:
            Log.error("Loading runtime failed from " + runtime_file)
            return

        self._chat_ids = runtime['chat_ids']
Example #4
0
    def load_settings(self):
        self._allowed_users = []

        settings_file = self._get_settings_file()
        try:
            settings = yaml.load(open(settings_file, 'r'))
            Log.info("Loading settings from " + settings_file)
        except:
            Log.error("Loading settings failed from " + settings_file)
            return

        self._token = settings['token']
        self._allowed_users = settings['users']
Example #5
0
    def handle_intercom_message(self, message: Message) -> Reply:
        """
        Handle an incoming message from another component

        :param message: Message to be sent
        :return: Message reply
        """
        try:
            return self._on_intercom_message(message)
        except Exception as e:
            Log.error(
                "Intercom message " + message.message_type + " failed:" + traceback.format_exc())
            return Reply(Reply.INTERCOM_STATUS_FAILURE, {'message': str(e)})
Example #6
0
    def __init__(self, code, name, params=None):
        if params is None:
            params = {}

        if self.COMPONENT_SINGLETON:
            if self.__class__.get_instance() is not None:
                Log.error(self.__class__.__name__ + ' cannot be allocated more than once')
                raise Exception(self.__class__.__name__ + ' cannot be allocated more than once')

        self._code = code
        self._name = name
        self._params = params

        Log.info('Daemon ' + self.get_code() + ' loaded')
Example #7
0
    def send_picture(self, file_name, caption=None, recipients=None):
        if file_name is None:
            return

        try:
            if recipients is None:
                recipients = self._allowed_users

            for recipient in recipients:
                chat_id = self.get_chat_id(recipient)
                if chat_id is not None:
                    self.get_bot().sendPhoto(chat_id=chat_id,
                                             photo=open(file_name, 'rb'),
                                             caption=caption)
                else:
                    Log.error('Unknown chat ID for user ' + recipient +
                              ', please send a message to this bot')
        except telegram.error.BadRequest:
            pass

        except FileNotFoundError:
            Log.error('File ' + file_name + ' not found')
Example #8
0
    def send(self) -> Reply:
        """
        Send a message to intercom channel
        :return: Message reply
        """
        from survy.core.app import App

        found = False
        res = {}
        status = Reply.INTERCOM_STATUS_SUCCESS

        recipients = self.get_recipients()
        for component in recipients:
            component_instance = App.components.get(component)

            if component_instance is not None:
                reply = component_instance.handle_intercom_message(self)

                if reply is not None:
                    if reply != Reply.INTERCOM_STATUS_NOT_FOUND:
                        # At least one component can handle our message
                        found = True

                        if reply == Reply.INTERCOM_STATUS_FAILURE:
                            # Set failure when at least one component replies with failure
                            status = Reply.INTERCOM_STATUS_FAILURE

                        res[component] = reply.to_dict()

            else:
                Log.error('Unknown component: ' + component)

        if not found:
            return Reply(Reply.INTERCOM_STATUS_NOT_FOUND)

        return Reply(status, res)
Example #9
0
    def load(cls):
        """
        Load YML rules file
        """
        cls._rules = []

        rules_file = cls._get_rules_file()
        try:
            rules = yaml.load(open(rules_file, 'r'))
            Log.info("Loading rules information from " + rules_file)
        except:
            Log.error("Loading rules information failed from " + rules_file)
            return

        for rule_code, rule_info in rules.items():

            event_instances = []
            action_instances = []
            condition_instances = []

            for event in rule_info['events']:
                if 'type' not in event:
                    Log.error('Missing "type" for event on rule "' + rule_code + '"')
                    continue

                payload = {}
                if 'payload' in event:
                    payload = event['payload']

                component = None
                if 'component_from' in event:
                    component = event['component_from']

                event_instances.append(Event(
                    message_from=component,
                    message_to='',
                    message_type=event['type'],
                    message_payload=payload
                ))

            for action in rule_info['actions']:
                if 'type' not in action:
                    Log.error('Missing "type" for action on rule "' + rule_code + '"')
                    continue

                payload = {}
                if 'payload' in action:
                    payload = action['payload']

                component = '_all'
                if 'component_to' in action:
                    component = action['component_to']

                async = False
                if 'async' in action:
                    async = action['async']

                delay = False
                if 'delay' in action:
                    delay = action['delay']

                action_instances.append(Action(
                    message_to=component,
                    message_from=RuleManager.get_instance().get_code(),
                    message_type=action['type'],
                    message_payload=payload,
                    action_async=async,
                    action_delay=delay
                ))

            if 'conditions' in rule_info:
                for condition in rule_info['conditions']:
                    if 'payload' in condition:
                        payload = condition['payload']
                        condition_instance = Condition(
                            condition_payload=payload
                        )
                        condition_instances.append(condition_instance)

            if 'name' not in rule_info:
                rule_info['name'] = rule_code

            rule = Rule(
                code=rule_code,
                name=rule_info['name'],
                events=event_instances,
                actions=action_instances,
                conditions=condition_instances
            )

            cls._rules.append(rule)