Exemplo n.º 1
0
def join_processing(server_obj, message):
    """
    Запрос на присоединение к чату. содержит имя чата (пустой join = дефолтный чат).
    Ответ сервера:
    200 - успешное присоединение к чату
    404 - чат не найден
    409 - пользователь уже в чате
    500 - ошибка сервера
    :param message:
    :param server_obj:
    """
    chat_name = message.body
    if not chat_name:  # Если приходит пустой join - понимаем как default chat
        chat_name = DEFAULT_CHAT
    try:
        server_obj.chat_controller.add_user_to_chat(
            server_obj.user, chat_name)  # Добавляем пользователя в чат
        response = Response(
            code=OK,
            action=message.action,
            body=
            f'User "{server_obj.user.account_name}" successfully joined chat {chat_name}'
        )
        response.add_header('name', chat_name)  # Формируем ответ
        for chat_member in server_obj.chat_controller.get_list_users(
                chat_name):  # Рассылка другим пользователям
            if chat_member.account_name != server_obj.user.account_name:  # двойная рассылка получается, исключаем себя
                chat_member.send_message(response)
        return response  # результат работы
    except (ChatNotFound, UserAlreadyInChat) as e:
        return Response(code=e.code, action=message.action, body=e.text)
Exemplo n.º 2
0
def add_contact_processing(server_obj, message):
    """
    # Добавление контакта. запрос содержит имя клиента, имя контакта.
    # Ответ сервера:
    # 200 - контакт добавлен
    # 400 - имя клиента или контакта отсутствует или некорректно
    # 409 - контакт уже есть в списке.
    """
    user = server_obj.user.account_name
    contact = message.body
    try:
        db.add_contact(user, contact)
        return Response(
            code=OK,
            action=message.action,
            body=f'Contact {contact} was successfully added to contact list')
    except (ContactAlreadyExists, UserNotFoundInDatabase) as e:
        return Response(code=e.code, action=message.action, body=e.text)
Exemplo n.º 3
0
def get_contact_processing(server_obj, message):
    """
    # Запрос на получение списка контактов. запрос содержит имя клиента
    # Ответ сервера:
    # 200 - Запрос обработан успешно
    # 101 - контакт, количество и номер контакта
    # 404 - нет контактов
    """
    user = server_obj.user.account_name
    try:
        contacts = db.get_contacts(user)
        response_messages = list()
        for contact in contacts:
            response_messages.append(contact.account_name)
        get_contact_response = Response(code=IMPORTANT_NOTICE, action=message.action, body=response_messages)
        server_obj.user.send_message(get_contact_response)
        return Response(code=OK, action=message.action, body=f'Contact list were send to {user}')
    except (NoContactsYet,) as e:
        return Response(code=e.code, action=message.action, body=e.text)
Exemplo n.º 4
0
def del_contact_processing(server_obj, message):
    """
    # Удаление контакта. запрос содержит имя клиента, имя контакта.
    # Ответ сервера:
    # 200 - контакт удален
    # 400 - имя клиента или контакта отсутствует или некорректно
    # 409 - контакта не существует в списке.
    """
    user = server_obj.user.account_name
    contact = message.body
    try:
        db.del_contact(user, contact)
        return Response(
            code=OK,
            action=message.action,
            body=f'Contact {contact} was successfully deleted from contact list'
        )
    except (ContactDoesNotExist, UserNotFoundInDatabase) as e:
        return Response(code=e.code, action=message.action, body=e.text)
Exemplo n.º 5
0
def presence_processing(server_obj, message):
    """
    Отправляется клиентом при подключении к серверу, содержит имя учетной записи.
    Ответ сервера:
    400 - имя учетной записи отсутствует или некорректно
    404 если клиент не найден в БД,
    500 - ошибка сервера
    :param message: Объект Request
    :param server_obj: объект Server
    :return: Объект Response
    """
    try:
        server_obj.user.account_name = message.body  # проверяем валидность через дескриптор
        if db.client_exists(message.body):  # ищем в базе
            return Response(
                code=OK,
                action=message.action,
                body=f'User {message.body} successfully found! Wow')
    except (UserNameIncorrect, UserNotFoundInDatabase) as e:
        return Response(code=e.code, action=message.action, body=e.text)
Exemplo n.º 6
0
 def inner_function(server_obj, request):
     if request.action in AUTHENTICATION_REQUIRED_ACTIONS:  # actions must be in authorized tuple
         if not server_obj.user.is_authenticated:
             return Response(
                 code=UNAUTHORIZED,
                 action=request.action,
                 body=f'Action {request.action} denied until unauthorized')
         else:
             return func(server_obj, request)
     else:
         return func(server_obj, request)
Exemplo n.º 7
0
def leave_processing(server_obj, message):
    """
    Запрос на выход из чата. содержит имя чата (Выйти из чата #all нельзя).
    Ответ сервера:
    200 - успешный выход из чата
    409 - Пользователь не является членом чата
    :param message:
    :param server_obj:
    """
    chat_name = message.body
    try:
        server_obj.chat_controller.delete_user_from_chat(server_obj.user, chat_name)  # Удаляем пользователя из чата
        response = Response(code=OK, action=message.action,
                            body=f'User "{server_obj.user.account_name}" successfully leaved chat {chat_name}')
        response.add_header('name', chat_name)  # Формируем ответ
        for chat_member in server_obj.chat_controller.get_list_users(chat_name):  # Рассылка другим пользователям
            chat_member.send_message(response)
        return response  # результат работы
    except (NoChatNameError, UserNotAMember, DefaultChatLeaveError, ChatDoesNotExist) as e:
        return Response(code=e.code, action=message.action, body=e.text)
Exemplo n.º 8
0
def authenticate_processing(server_obj, message):
    """
    Отправляется клиентом при авторизации. содержит имя учетной записи и хеш пароля.
    Ответ сервера:
    202 если пароль верный,
    400 - имя или пароль отсутствует или некорректно
    401 если пароль неверный,
    403 если пользователь заблокирован,
    404 если клиент не найден в БД.
    500 - ошибка сервера
    :param message: Объект Request
    :param server_obj: Объект server
    :return: Объект Response
    """
    account_name, password_hash = message.body
    try:
        server_obj.user.account_name = account_name  # проверяем валидность имени
        server_stored_password = db.get_client_by_username(account_name).password  # ищем пароль в БД
        if compare_hashes(server_stored_password, password_hash):
            server_obj.user.authenticate()
            return Response(code=ACCEPTED, action=message.action,
                            body=f'Authentication success! Welcome, {account_name}')
    except (UserNameIncorrect, UserNotFoundInDatabase, EmptyHashValue, PasswordsDidntMatch) as e:
        return Response(code=e.code, action=message.action, body=e.text)
Exemplo n.º 9
0
 def connection_lost(self, exc):
     """При потере коннекта пользователь удаляется из всех чатов, остальным приходит оповещение об этом"""
     print(
         f'Lost connection with client {self.user.account_name}. Reason: {exc}'
     )
     for chat_name in self.chat_controller.chats:
         user_disconnected_message = f'{self.user.account_name} has left chat {chat_name}'
         print(user_disconnected_message)
         response_user_disconnected = Response(
             action='leave',
             code=IMPORTANT_NOTICE,
             body=user_disconnected_message)
         # Удаляем из чатов юзера, который отключился
         try:
             self.chat_controller.delete_user_from_chat(
                 self.user, chat_name)
         except DefaultChatLeaveError:
             pass  # Этот чат покинуть можно только во время потери соединения
         for user in self.chat_controller.get_list_users(chat_name):
             # оповещаем юзеров в чатах об этом событии
             user.send_message(response_user_disconnected)
     self.user.transport.close()
Exemplo n.º 10
0
    def process_message(self, message):
        if not self.user.aes.secret:
            # Первое сообщение от клиента - зашифрованный публичным ключем RSA ключ сессии,
            # которым будут шифроваться все последующие сообщения
            decrypted_key = rsa_decipher_byte_string(message,
                                                     self.user.private)
            self.user.aes.secret = decrypted_key
        else:
            decrypted_message = self.user.aes.decrypt(message)
            print('processing message: ', decrypted_message)
            client_request = Request(decrypted_message)
            try:
                response_message = self.process_action(client_request)
                self.user.send_message(response_message)

            except KeyError:
                self.user.send_message(
                    Response(
                        code=SERVER_ERROR,
                        action=client_request.action,
                        body=
                        f'Action {client_request.action} do not allowed (not implemented yet)'
                    ))
Exemplo n.º 11
0
def msg_processing(server_obj, message):
    """
    # Текстовое сообщение. может быть групповым или личным. содержит имя отправителя, имя получателя, тело сообщения
    # Ответ сервера:
    # 100 - сообщение отправлено
    # 101 - сообщение не доставлено
    :param server_obj:
    :param message:
    :return: Response
    """
    recipient = message.headers['recipient']
    response_message = Response(code=BASIC_NOTICE, action=message.action, body=message.body)
    response_message.add_header('recipient', recipient)
    response_message.add_header('sender', message.headers['sender'])
    try:
        if recipient.startswith('#'):
            # TODO async for
            for chat_member in server_obj.chat_controller.get_list_users(recipient):
                chat_member.send_message(response_message)
            return Response(code=BASIC_NOTICE, action=message.action,
                            body=f'Message to {recipient} was sent successful')
        elif recipient.startswith('@'):
            for user in server_obj.chat_controller.get_list_users():
                if user.account_name == recipient[1:]:  # символ @ не нужен
                    user.send_message(response_message)
                    return Response(code=BASIC_NOTICE, action=message.action,
                                    body=f'Private message to {recipient} was sent successful')
                else:
                    return Response(code=NOT_FOUND, action=message.action, body=f'User {recipient} not online now')
        else:
            return Response(code=SERVER_ERROR, action=message.action, body='Server Error was happened')
    except (ChatDoesNotExist, ) as e:
        return Response(code=e.code, action=message.action, body=e.text)