Esempio n. 1
0
    def _handle_quit_msg(self, msg_dict):
        """
        Handles user quit message, when he safely closes the connection.
        @param msg_dict: JSON message (dictionary).
        @return: None.
        """
        self._client_info.set_quit_safety(True)

        # Если пользователь не автризовался в чате, то информация, что он покинул чат,
        # остаётся только на сервере - остальным пользователям ничего не отправляем
        client_login = self._client_info.get_login()
        if client_login.startswith('Anonymous') is False:
            client_contacts = self._db_connection.get_overall_client_contacts(
                client_login)
            if client_contacts:
                self._send_broadcast(client_contacts, msg_dict)

            self._main_window.remove_data_from_tab(
                'Clients', '{} ({})'.format(client_login,
                                            self._client_info.get_ip()))
        self._client_info.set_connection_state(False)

        self._main_window.add_data_in_tab(
            'Log', '[{}] Client {} ({}) has closed the connection.'.format(
                get_current_time(), client_login, self._client_info.get_ip()))
        # Deletes all client information which is being stored by the application
        server_holder.get_instance('ClientManager').delete_client(
            'login', client_login)
Esempio n. 2
0
    def _handle_error_msg(self, msg_dict):
        """
        Handles error message from the server (response).
        @param msg_dict: JSON-object. (message).
        @return: -
        """
        if str(msg_dict['response'])[0] in ['4', '5']:

            # Defines where to send the data
            if self._main_window.get_auth_state():
                time_str = '[{}] @Server>'.format(get_current_time())
                error_msg = 'Error {}: {}'.format(msg_dict['response'],
                                                  msg_dict['error'])
                self.add_log_signal.emit(time_str, error_msg)

            # if user is not logged in, checks the code
            else:
                if msg_dict['response'] == HTTPCode.UNAUTHORIZED:
                    self.show_message_box_signal.emit(
                        'Invalid authentication data!',
                        'Authentication has failed! Try again!')
                else:
                    self.show_message_box_signal.emit(
                        'Unknown error!',
                        'An unknown error has occured! Try again!')
Esempio n. 3
0
    def run(self):
        """
        Запускает процесс выполнения потока.
        @return: -
        """
        while self._client_info.is_connected():
            try:
                msg_bytes = self._socket.recv(1024)
            except OSError:
                if self._client_info.is_safe_quit() is False:
                    login = self._client_info.get_login()
                    ip = self._client_info.get_ip()

                    # Deletes client from the list of clients
                    self._main_window.remove_data_from_tab(
                        'Clients', '{} ({})'.format(login, ip))

                    # Shows message that client has closed his connection
                    self._main_window.add_data_in_tab(
                        'Log', '[{}] Client {} ({}) has timed out.'.format(
                            get_current_time(), login, ip))

                    # Deletes client from the client manager
                    self._client_manager.delete_client('ip', ip)

                    # Triggers threads to quit their routines
                    self._client_info.set_connection_state(False)
            else:
                self._input_buffer_queue.put(msg_bytes)
            time.sleep(self._wait_time)
Esempio n. 4
0
 def _handle_quantity_msg(self, msg_dict):
     """
     Handles message with amount of contacts of the current client.
     @param msg_dict: JSON-object. (message).
     @return: -
     """
     time_str = '[{}] @Server>'.format(get_current_time())
     alert_msg = 'Amount of contacts: {}'.format(msg_dict['quantity'])
     self.add_log_signal.emit(time_str, alert_msg)
Esempio n. 5
0
    def _handle_auth_msg(self, msg_dict):
        """
        Authenticates client by checking hist account in the database.
        @param msg_dict: JSON message (dictionary).
        @return: None.
        """
        client_login = msg_dict['user']['login']
        client_password = msg_dict['user']['password']

        authentication_success = self._db_connection.authenticate_client(
            client_login, client_password)
        if authentication_success is True:
            response_msg = JIMMessage(JIMMsgType.STC_ALERT,
                                      response=HTTPCode.OK,
                                      alert='Authentication is successful!')

            self._main_window.add_data_in_tab(
                'Log', '[{}] Client ({}) has logged in as {}.'.format(
                    get_current_time(), self._client_info.get_ip(),
                    client_login))

            self._main_window.add_data_in_tab(
                'Clients', '{} ({})'.format(client_login,
                                            self._client_info.get_ip()))
            self._client_info.set_login(client_login)
        else:
            # if user fails authentication, a reserved login is being taken (Anonymous####)
            client_login = self._client_info.get_login()

            response_msg = JIMMessage(JIMMsgType.STC_ERROR,
                                      response=HTTPCode.UNAUTHORIZED,
                                      error='Authentication has failed!')

            self._main_window.add_data_in_tab(
                'Log', '[{}] Client {} has failed authentication.'.format(
                    get_current_time(), self._client_info.get_ip()))

        self._sender.add_msg_to_queue(client_login, response_msg.serialize())
Esempio n. 6
0
 def run(self):
     """
     Runs thread routine.
     @return: -
     """
     while True:
         try:
             msg_bytes = self._socket.recv(1024)
         except OSError as e:
             self._main_window.add_data_in_tab(
                 'Log',
                 '[{}] @NCryptoChat> {}'.format(get_current_time(), str(e)))
             return
         else:
             self._input_buffer_queue.put(msg_bytes)
         time.sleep(self._wait_time)
Esempio n. 7
0
 def run(self):
     """
     Runs thread routine.
     @return: -
     """
     while True:
         if self._output_buffer_queue.qsize() > 0:
             msg_bytes = self._output_buffer_queue.get()
             try:
                 self._socket.send(msg_bytes)
             except OSError as e:
                 self._main_window.add_data_in_tab(
                     'Log',
                     '[{}] @NCryptoChat> {}'.format(get_current_time(),
                                                    str(e)))
         time.sleep(self._wait_time)
Esempio n. 8
0
    def _handle_leave_chat_msg(self, msg_dict):
        """
        Handles message when client leaves the specific chatroom.
        @param msg_dict: JSON message (dictionary).
        @return: None.
        """
        chatroom_name = msg_dict['room']
        client_login = self._client_info.get_login()

        response_msg = None
        try:
            if self._db_connection.del_client_from_chatroom(
                    client_login, chatroom_name) is False:
                raise SQLIntegrityError('{}, {}'.format(
                    client_login, chatroom_name))
        except SQLErrorNotFound as e:
            response_msg = JIMMessage(JIMMsgType.STC_ERROR,
                                      response=HTTPCode.NOT_FOUND,
                                      error=str(e))
        except SQLIntegrityError as e:
            response_msg = JIMMessage(JIMMsgType.STC_ERROR,
                                      response=HTTPCode.INTERNAL_SERVER_ERROR,
                                      error=str(e))
        else:
            response_msg = JIMMessage(
                JIMMsgType.STC_ALERT,
                response=HTTPCode.OK,
                alert='You have left \'{}\' chatroom!'.format(chatroom_name))

            chatroom_participants = self._db_connection.get_chatroom_clients(
                chatroom_name)
            if chatroom_participants:
                self._send_broadcast(chatroom_participants, msg_dict)

            self._main_window.add_data_in_tab(
                'Log', '[{}] Client {} ({}) has left {}.'.format(
                    get_current_time(), client_login,
                    self._client_info.get_ip(), chatroom_name))
        finally:
            self._sender.add_msg_to_queue(client_login,
                                          response_msg.serialize())
Esempio n. 9
0
    def _handle_get_contacts_msg(self):
        """
        Sends information to client with amount of his contacts and list of contacts logins.
        @return: None.
        """
        client_login = self._client_info.get_login()

        self._main_window.add_data_in_tab(
            'Log', '[{}] Client {} ({}) requested list of contacts.'.format(
                get_current_time(), client_login, self._client_info.get_ip()))

        client_contacts = self._db_connection.get_client_contacts(client_login)
        client_contacts.extend(
            self._db_connection.get_client_chatrooms(client_login))
        if client_contacts:
            msgs_to_send = [
                JIMMessage(JIMMsgType.STC_QUANTITY,
                           response=HTTPCode.ACCEPTED,
                           quantity=len(client_contacts))
            ]

            for login in client_contacts:
                msgs_to_send.append(
                    JIMMessage(JIMMsgType.STC_CONTACTS_LIST,
                               action='contacts_list',
                               login=login))

            for msg_to_send in msgs_to_send:
                self._sender.add_msg_to_queue(client_login,
                                              msg_to_send.serialize())

                # TODO: delay (tmp solution) to avoid sticking of messages
                time.sleep(0.1)
        else:
            response_msg = JIMMessage(JIMMsgType.STC_ERROR,
                                      response=HTTPCode.NOT_FOUND,
                                      error='No contacts were found!')
            self._sender.add_msg_to_queue(client_login,
                                          response_msg.serialize())
Esempio n. 10
0
    def _handle_alert_msg(self, msg_dict):
        """
        Handles an ordinary answer from the server (response).
        @param msg_dict: JSON-object. (message).
        @return: -
        """
        if str(msg_dict['response'])[0] in ['1', '2']:

            # Defines where to send the data
            if self._main_window.get_auth_state():
                time_str = '[{}] @Server>'.format(get_current_time())
                alert_msg = 'Alert {}: {}'.format(msg_dict['response'],
                                                  msg_dict['alert'])

                self.add_log_signal.emit(time_str, alert_msg)

                self._handle_alert_message(msg_dict['alert'])

            # if user is not logged in, checks the code
            else:
                if msg_dict['response'] == HTTPCode.OK:
                    self._main_window.set_auth_state(True)
                    self.open_chat_signal.emit()
Esempio n. 11
0
    def _handle_del_contact_msg(self, msg_dict):
        """
        Removes specific contact from the client list.
        @param msg_dict: JSON message (dictionary).
        @return: None.
        """
        contact_login = msg_dict['login']
        client_login = self._client_info.get_login()
        response_msg = None
        try:
            if self._db_connection.del_contact(client_login,
                                               contact_login) is False:
                raise SQLIntegrityError('{}, {}'.format(
                    client_login, contact_login))
        except SQLErrorNotFound as e:
            response_msg = JIMMessage(JIMMsgType.STC_ERROR,
                                      response=HTTPCode.NOT_FOUND,
                                      error=str(e))
        except SQLIntegrityError as e:
            response_msg = JIMMessage(JIMMsgType.STC_ERROR,
                                      response=HTTPCode.INTERNAL_SERVER_ERROR,
                                      error=str(e))
        else:
            self._main_window.add_data_in_tab(
                'Log',
                '[{}] Client {} ({}) has deleted client {} from his contacts.'.
                format(get_current_time(), client_login,
                       self._client_info.get_ip(), contact_login))

            response_msg = JIMMessage(
                JIMMsgType.STC_ALERT,
                response=HTTPCode.OK,
                alert='Contact \'{}\' has been successfully removed!'.format(
                    contact_login))
        finally:
            self._sender.add_msg_to_queue(client_login,
                                          response_msg.serialize())