Exemplo n.º 1
0
    def __init__(self, message):
        self.result = Message()
        self.error = False
        self.msg = message
        self.user = None

        self.set_basic_params()
        self.db_connect = DatabaseConnection()
Exemplo n.º 2
0
 def receive(self):
     sock = self.get_socket()
     m = Message()
     headers = Receiver.receive_headers(sock)
     m.set_header_bytes(headers)
     content_length = m.get_header_param(MESSAGE_CONTENT_LENGTH)
     body = Receiver.receive_body(sock, content_length)
     m.set_body_bytes(body)
     return m
Exemplo n.º 3
0
    def send_message(self, client_list, current_username):
        from xcomm.message import Message
        message = Message(body=self.msg.body)
        message.add_header_param(MESSAGE_ACTION,
                                 MESSAGE_ACTION_RECVMESSAGE_CODE)

        # Adding info about user and current date&time
        message.add_body_param(MESSAGE_ACTION_RECVMESSAGE_USER,
                               current_username)
        time_now = datetime.datetime.now()
        message.add_body_param(MESSAGE_ACTION_RECVMESSAGE_TIMESTAMP,
                               time_now.timestamp())

        logger.debug("Directing message to all users in room: " +
                     message.get_complete_message().replace('\0', '\n'))

        message = message.convert_message_to_bytes()

        for client in client_list:
            client.client_socket.sendall(message)
Exemplo n.º 4
0
class ActionBase(metaclass=ABCMeta):
    errors = {}

    def __init__(self, message):
        self.result = Message()
        self.error = False
        self.msg = message
        self.user = None

        self.set_basic_params()
        self.db_connect = DatabaseConnection()

    def set_basic_params(self):
        self.result.add_header_param(MESSAGE_ACTION, self.get_action_number())

    @abstractmethod
    def get_action_number(self):
        pass

    @abstractmethod
    def execute(self, *args, **kwargs):
        pass

    def set_error_with_status(self, status):
        self.error = True
        self.result.add_body_param(MESSAGE_STATUS, status)

    def set_status_ok(self):
        self.result.add_body_param(MESSAGE_STATUS, MESSAGE_STATUS_OK)

    def get_action_result(self):
        return self.result

    def get_error(self):
        return self.error
Exemplo n.º 5
0
    def send_message(f: types.FunctionType, *args, **kwargs):
        """

        :param f: request action
        :param args:
        :param kwargs: message content
        :return:
        """
        try:
            body = kwargs.get('body')
            headers = {}
            headers.update({'Action': CLIENT_SEND_ACTIONS[f.__name__]})
            message = Message(header=headers, body=body)
            socket_, token = f(*args, **kwargs)

            logger.debug("Sending to server: {}".format(
                message.convert_message_to_bytes().decode()))

            if token:
                message.add_header_param(TOKEN_KEY, token)
            socket_.sendall(message.convert_message_to_bytes())
        except KeyError:
            logger.debug("Sending ERROR, invalid action name: {}".format(
                f.__name__))
            raise KeyError(f"There is no action for {f.__name__} function")
Exemplo n.º 6
0
    def always_listen(self):
        while True:
            self.message = Message()
            msg = b""
            while DELIMITER_BYTE * 2 not in msg:
                msg += self.client_socket.recv(RECEIVE_BYTES_LIMIT)

            self.message.set_header_bytes(msg)
            content_length = int(
                self.message.get_header_param(MESSAGE_CONTENT_LENGTH))

            msg = b""
            while len(msg) < content_length:
                msg += self.client_socket.recv(RECEIVE_BYTES_LIMIT)

            self.message.set_body_bytes(msg)
            self.logger.debug(
                f"({self.client_address}) -> " +
                self.message.get_complete_message().replace("\0", "\n"))

            # Serve message
            action = ActionProvider.get_action_for(self.message)

            if action is not None:
                kwargs = {}
                if isinstance(action, (SendMessageAction, LoginAction)):
                    kwargs['server'] = self.server
                if isinstance(action, LoginAction):
                    kwargs['client'] = self
                try:
                    action.execute(**kwargs)
                except DatabaseError as e:
                    action.set_error_with_status(DatabaseException.message)

                response = action.get_action_result()
                self.client_socket.sendall(response.convert_message_to_bytes())
                self.logger.debug(
                    f"({self.client_address}) <- " +
                    response.get_complete_message().replace("\0", "\n"))
Exemplo n.º 7
0
class Client:
    def __init__(self, client_socket, client_address, server):
        self.client_socket = client_socket
        self.client_address = client_address
        self.message = None
        self.logger = logging.getLogger("Client")
        self.server = server
        self.user = None

    def start(self):
        recv_thread = threading.Thread(target=self.always_listen, daemon=True)
        recv_thread.start()

    @disconnect_handler
    def always_listen(self):
        while True:
            self.message = Message()
            msg = b""
            while DELIMITER_BYTE * 2 not in msg:
                msg += self.client_socket.recv(RECEIVE_BYTES_LIMIT)

            self.message.set_header_bytes(msg)
            content_length = int(
                self.message.get_header_param(MESSAGE_CONTENT_LENGTH))

            msg = b""
            while len(msg) < content_length:
                msg += self.client_socket.recv(RECEIVE_BYTES_LIMIT)

            self.message.set_body_bytes(msg)
            self.logger.debug(
                f"({self.client_address}) -> " +
                self.message.get_complete_message().replace("\0", "\n"))

            # Serve message
            action = ActionProvider.get_action_for(self.message)

            if action is not None:
                kwargs = {}
                if isinstance(action, (SendMessageAction, LoginAction)):
                    kwargs['server'] = self.server
                if isinstance(action, LoginAction):
                    kwargs['client'] = self
                try:
                    action.execute(**kwargs)
                except DatabaseError as e:
                    action.set_error_with_status(DatabaseException.message)

                response = action.get_action_result()
                self.client_socket.sendall(response.convert_message_to_bytes())
                self.logger.debug(
                    f"({self.client_address}) <- " +
                    response.get_complete_message().replace("\0", "\n"))
Exemplo n.º 8
0
 def send(self, message: Message):
     sock = self.get_socket()
     return sock.sendall(message.convert_message_to_bytes())