Exemplo n.º 1
0
    def _on_intercom_message_complex_message(self, message: Message) -> Reply:
        payload = message.message_payload

        filename = message.message_payload['filename']
        if not os.path.isfile(filename) or not App.can_access_file(filename):
            return Reply(Reply.INTERCOM_STATUS_NON_BLOCKING_FAILURE)

        caption = os.path.basename()
        if 'caption' in message.message_payload:
            caption = message.message_payload[filename]

        recipients = None
        if 'to' in payload:
            recipients = re.split(r'\s*,\s*', payload['to'])

        if message == self.INTERCOM_MESSAGE_DO_PHOTO_MESSAGE:
            self.send_picture(file_name=filename,
                              caption=caption,
                              recipients=recipients)

        elif message == self.INTERCOM_MESSAGE_DO_VIDEO_MESSAGE:
            self.send_video(file=filename,
                            caption=caption,
                            recipients=recipients)

        elif message == self.INTERCOM_MESSAGE_DO_DOCUMENT_MESSAGE:
            self.send_video(file=filename,
                            caption=caption,
                            recipients=recipients)

        return Reply(Reply.INTERCOM_STATUS_SUCCESS)
Exemplo n.º 2
0
    def _on_do_fire(self, message: Message) -> Reply:
        payload = message.message_payload
        signal = SignalRepo.get_by_code(device_code=payload['device'],
                                        sub_code=payload['sub'])
        if signal is None:
            return Reply(Reply.INTERCOM_STATUS_FAILURE)

        signal.fire()
        return Reply(Reply.INTERCOM_STATUS_SUCCESS)
Exemplo n.º 3
0
    def reload(self):
        """
        Reload settings
        :return:
        """
        if self._reload() is True:
            return Reply(Reply.INTERCOM_STATUS_SUCCESS)

        elif self._reload() is False:
            return Reply(Reply.INTERCOM_STATUS_FAILURE)

        return None
Exemplo n.º 4
0
    def _on_intercom_message_send_chat(self, message: Message) -> Reply:
        payload = message.message_payload

        recipients = None
        if 'to' in payload:
            recipients = re.split(r'\s*,\s*', payload['to'])

        self.send_message(text=payload['text'], recipients=recipients)
        return Reply(Reply.INTERCOM_STATUS_SUCCESS)
Exemplo n.º 5
0
    def _on_say_text(self, message: Message):
        payload = message.message_payload

        params_fail = self.check_required_parameters(payload, ['text'])
        if params_fail:
            return params_fail

        self.say_text(payload['text'])
        return Reply(Reply.INTERCOM_STATUS_SUCCESS)
Exemplo n.º 6
0
    def _control_command(self, data):
        params = self.get_cam_params()

        data['usr'] = params['user']
        data['pwd'] = params['pass']

        url = 'http://' + params['host'] + '/CGIProxy.fcgi?' + urllib.parse.urlencode(data)

        try:
            req = urllib.request.Request(url)
            res = urllib.request.urlopen(req).read().decode("utf-8")

            if '<result>0</result>' in res:
                return Reply(Reply.INTERCOM_STATUS_SUCCESS)
        except:
            pass

        return Reply(Reply.INTERCOM_STATUS_FAILURE)
Exemplo n.º 7
0
    def _decoder_control_command(self, command):
        params = self.get_cam_params()

        data = {
            'user': params['user'],
            'pwd': params['pass'],
            'command': str(command)
        }

        try:
            url = 'http://' + params['host'] + '/decoder_control.cgi?' + urllib.parse.urlencode(data)
            req = urllib.request.Request(url)
            res = urllib.request.urlopen(req).read().decode("utf-8")

            if 'ok.' in res:
                return Reply(Reply.INTERCOM_STATUS_SUCCESS)
        except:
            pass

        return Reply(Reply.INTERCOM_STATUS_FAILURE)
Exemplo n.º 8
0
    def _on_cam_command_go_preset(self, message: Message) -> Reply:
        payload = message.message_payload

        if 'position' in payload:
            params = {
                'cmd': 'ptzGotoPresetPoint',
                'name': payload['position'],
            }

            return self._control_command(params)

        return Reply(Reply.INTERCOM_STATUS_FAILURE)
Exemplo n.º 9
0
    def _on_line(self, line):
        if len(line) == 0:
            return

        try:
            message = json.loads(line)

            if 'payload' not in message:
                message['payload'] = {}

            reply = TCPSocketManager.get_instance().send_intercom_message(
                message_type=message['message'],
                message_payload=message['payload']
            )

        except Exception as e:
            reply = Reply(Reply.INTERCOM_STATUS_FAILURE, {'message': str(e)})

        self._lock.acquire()
        self.request.sendall(bytes(json.dumps(reply.to_dict()) + "\n", 'utf-8'))
        self._lock.release()
Exemplo n.º 10
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)})
Exemplo n.º 11
0
    def _on_intercom_message(self, message: Message) -> Reply:
        """
        Internally handle an incoming message. Protected method to be overridden.

        :param message: Message to be sent
        :return: Message reply
        """

        if message == self.INTERCOM_MESSAGE_DO_RELOAD:
            return self.reload()

        return Reply(Reply.INTERCOM_STATUS_NOT_FOUND, {
            'message': 'Task not found in this component'
        })
Exemplo n.º 12
0
    def check_required_parameters(cls, payload, required_params):
        """
        Check a list of parameters that must be defined in payload.

        :param payload: Payload to be verified
        :param required_params: A list of required parameters name
        :return: False on success or a list of errors
        """
        for required_param in required_params:
            if required_param not in payload:
                return Reply(Reply.INTERCOM_STATUS_FAILURE, {
                    'Missing ' + required_param + ' parameter'
                })

        return False
Exemplo n.º 13
0
    def _on_intercom_message_cam_action(self, message: Message) -> Reply:
        payload = message.message_payload

        cams = payload['cam'].split(',')
        for cam in cams:
            recipients = None
            if 'to' in payload:
                recipients = re.split(r'\s*,\s*', payload['to'])

            # Async images send
            threading.Thread(target=self._on_cam_action,
                             kwargs={
                                 'cam': cam,
                                 'recipients': recipients
                             }).start()

        return Reply(Reply.INTERCOM_STATUS_SUCCESS)
Exemplo n.º 14
0
    def on_message(self):
        m = re.search(r'^/(?P<component>.+?)/(?P<task>.+)$', self.path)
        if m:
            if 'Content-Length' in self.headers:
                content_len = int(self.headers['Content-Length'])
            else:
                content_len = 0

            if content_len > 0:
                raw_data = self.rfile.read(content_len)
                payload = json.loads(raw_data.decode('utf-8'))
            else:
                payload = None

            component = m.group('component')
            task = m.group('task')

            return HttpManager.get_instance().create_intercom_message(
                component, task, payload).send()

        return Reply(status=Reply.INTERCOM_STATUS_FAILURE,
                     payload={'message': 'Incorrect format'})
Exemplo n.º 15
0
    def _on_cam_action(self, message: Message) -> Reply:
        payload = message.message_payload

        cams = payload['cam'].split(',')
        for cam in cams:
            recipients = None
            if 'to' in payload:
                recipients = re.split(r'\s*,\s*', payload['to'])

            if message == self.INTERCOM_MESSAGE_DO_SEND_CAM_SNAPSHOT:
                self._send_cam_snapshot(cam=cam, recipients=recipients)

            elif message == self.INTERCOM_MESSAGE_DO_SEND_CAM_VIDEO:
                duration = 10
                if 'duration' in message.message_payload:
                    duration = message.message_payload['duration']

                self._send_cam_video(cam=cam,
                                     recipients=recipients,
                                     duration=duration)

        return Reply(Reply.INTERCOM_STATUS_SUCCESS)
Exemplo n.º 16
0
    def _on_learn_start(self, message: Message) -> Reply:
        payload = message.message_payload

        self._last_learning_signal = None
        self._learning_signal = Signal(
            code='',
            manager=None,
            device_name=payload['device'],
            sub_name=payload['sub'],
        )

        if self._learn_timeout is not None:
            self._learn_timeout.cancel()

        self._learn_timeout = threading.Timer(interval=self.LEARN_TIMEOUT,
                                              function=self._on_learn_timeout)
        self._learn_timeout.start()

        Log.info("Learning start: " + str(self._learning_signal))
        self.send_intercom_message(self.INTERCOM_MESSAGE_EVENT_LEARN_START,
                                   self._learning_signal.to_dict())

        return Reply(Reply.INTERCOM_STATUS_SUCCESS)
Exemplo n.º 17
0
    def _run_client(self, message: Message) -> Reply:
        payload = message.message_payload
        url = payload['url']

        data = None
        if 'data' in payload:
            data = payload['data']

        # Post request
        if 'method' in payload and payload['method'].lower() == 'post':
            if data is not None:
                data = {}
            req = urllib.request.Request(url, data)

        # Get request
        else:
            if data is not None:
                url += '?' + urllib.parse.urlencode(data)
            req = urllib.request.Request(url)

        urllib.request.urlopen(req).read()

        return Reply(Reply.INTERCOM_STATUS_SUCCESS)
Exemplo n.º 18
0
    def _on_learn_end(self):
        Log.info("Exiting learning mode")

        self._learning_signal = None
        self._learn_timeout.cancel()
        return Reply(Reply.INTERCOM_STATUS_SUCCESS)