def __req_auth_handler(self, i_req, client, *args):
        """ Mathod the handler authorization request """

        other_clients = args[0]
        user = [u for u, c in self.users.items() if c == client]
        if len(user) == 0:
            self.logger.warning(f'AUTH: user not found')
            return
        user = user[0]
        cl, key = self.client_keys[user]
        if cl != client:
            self.logger.warning('AUTH: connection sockets not equals')
            return
        password = decrypt_password(key, i_req.body)
        if password is None:
            self.logger.warning('AUTH: decrypt error')
            return
        password_hash = get_hash_password(password, user.encode())
        if not self.storage.authorization_user(user, password_hash):
            self.__send_to_client(client, Response(UNAUTHORIZED))
            self.clients.remove(client)
            self.users.pop(user)
            return
        self.storage.login_user(user, client.getpeername()[0])
        self.__send_to_client(client, Response(OK))
        self.__send_to_all(other_clients, Response(CONNECTED, user))
 def __send_image_bytes(self, client, img_bytes):
     avatar_part = 512
     for i in range(0, len(img_bytes), avatar_part):
         part = b64encode(img_bytes[i:i + avatar_part])
         part_resp = Response(FILE_ANSWER, part.decode())
         self.__send_to_client(client, part_resp)
     self.__send_to_client(client, Response(FILE_ANSWER))
 def __execute_command(self, command, *args):
     if command in self.commands:
         answer = self.commands[command](*args)
         if answer is False:
             return Response(SERVER_ERROR, 'Command error')
         elif isinstance(answer, list):
             answer = [str(a) for a in answer]
             return Response(ANSWER, answer)
         elif answer is None:
             return Response(ANSWER, 'Done')
         return Response(ANSWER, answer)
     else:
         return Response(INCORRECT_REQUEST, 'Command not found')
    def __req_presence_handler(self, i_req, client, *args):
        """ Mathod the handler presence request """

        prv, pub = gen_keys()
        self.client_keys[i_req.body] = (client, prv)
        self.__send_to_client(client, Response(AUTH,
                                               pub.export_key().decode()))
 def __req_send_image_handler(self, i_req, client, *args):
     avatar = self.storage.get_avatar(i_req.body)
     if avatar:
         sender_thread = ServerThread(
             lambda: self.__send_image_bytes(client, avatar), self.logger)
         sender_thread.start()
     else:
         self.__send_to_client(client, Response(FILE_ANSWER))
 def __req_end_recv_image_handler(self, i_req, client, *args):
     user = [u for u, c in self.users.items() if c == client].pop()
     if user not in self.images.keys():
         self.logger.warning('Image is empty')
         return
     user_avatar = self.images.pop(user)
     self.storage.set_avatar(user, user_avatar)
     self.__send_to_client(client, Response(FILE_ANSWER))
 def __req_recv_image_handler(self, i_req, client, *args):
     user = [u for u, c in self.users.items() if c == client].pop()
     body = b64decode(i_req.body.encode())
     if user in self.images.keys():
         self.images[user] += body
     else:
         self.images[user] = body
     self.__send_to_client(client, Response(FILE_ANSWER))
    def __req_message_handler(self, i_req, client, *args):
        """ Mathod the handler message request """

        other_clients = args[0]
        msg = Msg.from_dict(i_req.body)
        self.storage.user_stat_update(msg.sender, ch_sent=1)
        if msg.to.upper() != 'ALL' and msg.to in self.users:
            self.storage.user_stat_update(msg.to, ch_recv=1)
            self.storage.add_message(msg.sender, msg.to, msg.text)
            self.__send_to_client(self.users[msg.to],
                                  Response(LETTER, str(msg)))
        else:
            self.__send_to_all(other_clients, Response(LETTER, str(msg)))
            for u in self.storage.get_users_online():
                if str(u) == msg.sender:
                    continue
                self.storage.user_stat_update(str(u), ch_recv=1)
                self.storage.add_message(msg.sender, str(u), msg.text)
    def __req_accept_chat_handler(self, i_req, client, *args):
        """ Mathod the handler accept chat request """

        msg = Msg.from_dict(i_req.body)
        if msg.to not in self.users:
            self.logger.warning(f'{msg.to} not found')
            return
        self.__send_to_client(self.users[msg.to],
                              Response(ACCEPT_CHAT, str(msg)))
 def __client_disconnect(self, client):
     self.clients.remove(client)
     user = [u for u, c in self.users.items() if c == client].pop()
     self.users.pop(user)
     self.storage.logout_user(user)
     disconnection_response = Response(DISCONNECTED, user)
     self.logger.debug(disconnection_response)
     for cl in self.clients:
         send_data(cl, disconnection_response)
    def __req_message_handler(self, i_req, client, *args):
        """ Mathod the handler message request """

        other_clients = args[0]
        msg = Msg.from_dict(i_req.body)
        self.storage.user_stat_update(msg.sender, ch_sent=1)
        if msg.to.upper() != '@ALL' and msg.to in self.users:
            self.storage.user_stat_update(msg.to, ch_recv=1)
            self.storage.add_message(msg.sender, msg.to, msg.text)
            self.__send_to_client(self.users[msg.to],
                                  Response(LETTER, str(msg)))
        else:
            text = b64decode(msg.text).decode().lower()
            spam_filter = [s for s in self.SPAM if s in text]
            if len(spam_filter) > 0:
                self.logger.warning('SPAM DETECT')
                return
            self.storage.add_message_to_room(msg.to.upper()[1:], msg.text,
                                             msg.sender)

            self.__send_to_all(other_clients, Response(LETTER, str(msg)))
    def __send_responses(self, requests, o_clients):
        """ Method the sender of responses to clients """

        for client, i_req in requests.items():
            other_clients = [c for c in o_clients if c != client]
            self.logger.info(client)
            self.logger.info(i_req)
            action = i_req.action
            if action in self.request_handlers:
                self.request_handlers[action](i_req, client, other_clients)
            else:
                self.__send_to_client(client, Response(INCORRECT_REQUEST))
                self.logger.error(f'Incorrect request:\n {i_req}')
 def __client_disconnect(self, client):
     self.clients.remove(client)
     user = next(iter([u for u, c in self.users.items() if c == client]),
                 None)
     if not user:
         self.blacklist.append(client.getpeername()[0])
         return
     self.users.pop(user)
     self.storage.logout_user(user)
     disconnection_response = Response(DISCONNECTED, user)
     self.logger.debug(disconnection_response)
     for cl in self.clients:
         send_data(cl, disconnection_response)
Beispiel #14
0
 def authorization(self):
     """ Method of authorization on server """
     pr_req = Request(RequestAction.PRESENCE, self.user.username)
     self.__send_request(pr_req)
     resp = self.__get_response()
     if resp is None:
         return Response(SERVER_ERROR)
     if resp.code != AUTH:
         return resp
     enc_pass = encrypt_rsa(import_pub_key(resp.message.encode()),
                            self.user.password)
     auth_req = Request(RequestAction.AUTH, enc_pass.decode())
     self.__send_request(auth_req)
     return self.__get_response()
    def __get_requests(self, i_clients):
        """ Method the handler of client requests """

        requests = {}
        for client in i_clients:
            try:
                request = get_data(client)
                requests[client] = request

                if request.action == RequestAction.PRESENCE:
                    if request.body in self.users:
                        requests.pop(client)
                        send_data(client, Response(CONFLICT))
                        self.clients.remove(client)
                    else:
                        self.users[request.body] = client
                elif request.action == RequestAction.QUIT:
                    self.__client_disconnect(client)
            except (ConnectionError, ValueError):
                self.__client_disconnect(client)
            except Exception as e:
                raise e
        return requests