Example #1
0
    def request(self, c_socket):
        num_left = 0

        try:
            my_leave_request = input(
                "What room(s) do you wish to leave? comma separated list for multiple joins: "
            )
            if not my_leave_request:
                raise ValueError

            adjust_leave = my_leave_request.lower()
            leave_list = adjust_leave.split(",")

        except ValueError as e:
            error = base.Error()
            error.empty_string()
            error.receive()
            return -1

        for room in leave_list:
            if room in c.MY_ROOMS.keys():
                del c.MY_ROOMS[room]
                self.data = room.rstrip()
                to_send = self.prepare_msg_out('LeaveMessage')
                c_socket.send(to_send)
                num_left += 1
            else:
                error = base.Error()
                error.room_missing(room)
                error.receive()

        return len(leave_list) - num_left
Example #2
0
    def request(self, c_socket):
        num_joined = 0
        try:
            error = base.Error()
            my_join_request = input(
                "What room(s) do you wish to join? comma separated list for multiple joins: "
            )
            if not my_join_request:
                error.empty_string()
                raise ValueError

            adjust_join = my_join_request.lower()
            join_list = adjust_join.split(",")
        except ValueError:
            error.receive()
            return -1

        for room in join_list:
            if room in c.ALL_ROOMS.keys():
                if room not in c.MY_ROOMS.keys():
                    self.data = room.rstrip()
                    to_send = self.prepare_msg_out('JoinMessage')
                    c_socket.send(to_send)
                    num_joined += 1
                else:
                    error = base.Error()
                    error.join_duplicate_user(c.my_username, room)
                    error.receive()
            else:
                error = base.Error()
                error.room_missing(room)
                error.receive()

        return len(join_list) - num_joined
Example #3
0
    def request(self, c_socket):
        num_sent = 0

        recipients = self.choose_recipients()

        if len(recipients) < 1:
            return -1

        try:
            my_msg = input("Msg: ")
            error = base.Error()
            if not my_msg:
                error.empty_string()
                raise ValueError
            if len(my_msg) > base.MSG_MAX:
                error.data_exceeds_len()
                raise ValueError
        except ValueError:

            error.receive()

            return -1

        self.data = my_msg

        for room in recipients:
            self.dest = room.rstrip()
            to_send = self.prepare_msg_out('ChatMessage')
            c_socket.send(to_send)
            num_sent += 1

        return len(recipients) - num_sent
Example #4
0
    def choose_recipients():
        print(
            "Enter rooms to message as comma separated list (must be joined to send)"
        )
        adjusted = ""
        try:
            my_recipients = input("Rooms to msg: ")
            error = base.Error()

            if not my_recipients:
                error.empty_string()
                raise ValueError

            adjusted = my_recipients.lower()
            adjusted = my_recipients.split(',')

            for room in adjusted:
                if room not in c.MY_ROOMS.keys():
                    adjusted.remove(room)
                    error.room_missing(room)
                    raise ValueError
        except ValueError:
            error.receive()

        return adjusted
Example #5
0
def establish_connection(ip, port):
    try:
        c_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        c_socket.connect((ip, port))
        c_socket.setblocking(False)
    except socket.error as se:
        error = base.Error()
        error.broken_connection(ip)
        error.receive()
        sys.exit(f'EXITING')

    return c_socket
Example #6
0
    def request_open(self):
        try:
            from_user = input("Username: ")
            error = base.Error()

            if not from_user:
                error.empty_string()
                raise ValueError
            elif len(from_user) > base.NAME_MAX:
                error.name_exceeds_len()
                raise ValueError
            c.my_username = from_user.lower().rstrip()
        except ValueError:
            error.receive()
            return None

        self.sender = c.my_username.rstrip()
        to_send = self.prepare_msg_out('ConnectionMessage')
        return to_send
Example #7
0
def json_msg_decoder(to_decode):
    if '__type__' in to_decode and to_decode['__type__'] == 'Message':
        return msg.Message(to_decode['timestamp'], to_decode['sender'],
                           to_decode['dest'], to_decode['data'])
    if '__type__' in to_decode and to_decode['__type__'] == 'CreateRoomMessage':
        return CreateRoomMessage(to_decode['timestamp'], to_decode['sender'],
                                 to_decode['dest'], to_decode['data'])
    if '__type__' in to_decode and to_decode['__type__'] == 'JoinMessage':
        return JoinMessage(to_decode['timestamp'], to_decode['sender'],
                           to_decode['dest'], to_decode['data'])
    if '__type__' in to_decode and to_decode['__type__'] == 'ConnectionMessage':
        return ConnectionMessage(to_decode['timestamp'], to_decode['sender'],
                                 to_decode['dest'], to_decode['data'])
    if '__type__' in to_decode and to_decode['__type__'] == 'LeaveMessage':
        return LeaveMessage(to_decode['timestamp'], to_decode['sender'],
                            to_decode['dest'], to_decode['data'])
    if '__type__' in to_decode and to_decode['__type__'] == 'ChatMessage':
        return ChatMessage(to_decode['timestamp'], to_decode['sender'],
                           to_decode['dest'], to_decode['data'])
    if '__type__' in to_decode and to_decode['__type__'] == 'Error':
        return base.Error(to_decode['code'], to_decode['data'])
    return to_decode
Example #8
0
    def request(self, c_socket):

        try:
            my_room = input("New room name: ")
            error = base.Error()
            if not my_room:
                error.empty_string()
                raise ValueError
            if my_room in c.ALL_ROOMS:
                error.create_duplicate_room(my_room)
                raise ValueError
            if len(my_room) > base.NAME_MAX:
                error.name_exceeds_len()
                raise ValueError
        except ValueError as e:
            error.receive()
            return False

        self.data = my_room.rstrip()

        msg_out = self.prepare_msg_out('CreateRoomMessage')
        c_socket.send(msg_out)
        return True
Example #9
0
def main():
    c_socket = ms.establish_connection(base.SERVER_IP, base.SERVER_PORT)
    ms.manage_keepalive(c_socket)

    attempt_connect = 0
    action = True

    while attempt_connect == 0:
        open_msg = mm.ConnectionMessage()
        attempt_connect = open_msg.request(c_socket, 'CONNECT')

    # display intro text to user
    ms.intro()

    while True:

        out = None
        wait = True

        while action or wait:
            action = ms.receive_msg_in(action, c_socket)
            if not action:
                wait = False
            else:
                wait = True

        selection = ms.process_user_choice()

        if selection == '$create$':
            msg = mm.CreateRoomMessage(None, c.my_username, 'SERVER', None)
            status = msg.request(c_socket)
            if status:
                action = True
        elif selection == '$join$':
            msg = mm.JoinMessage(None, c.my_username, 'SERVER', None)
            num_joined = msg.request(c_socket)
            if num_joined != 0:
                warning = base.Error()
                warning.warning_join()
                warning.receive()
            action = True
        elif selection == '$view_all$':
            all_rooms = ms.list_all_rooms()
            if all_rooms != len(c.ALL_ROOMS):
                print('SYSTEM ERROR: printing all rooms')
            action = False
        elif selection == '$menu$':
            ms.intro()
            action = False
        elif selection == '$list$':
            list_mem = ms.list_room_members()
            if list_mem == -1:
                error = base.Error()
                error.room_missing('room')
                error.receive()
            action = False
        elif selection == '$msg$':
            msg = mm.ChatMessage(None, c.my_username, None, None)
            num_sent = msg.request(c_socket)
            if num_sent < 0:
                action = False
            else:
                action = True
        elif selection == '$leave$':
            msg = mm.LeaveMessage(None, c.my_username, 'Server', None)
            num_left = msg.request(c_socket)
            if num_left < 0:
                action = False
            else:
                action = True
        elif selection == '$quit$':
            msg = mm.ConnectionMessage(None, c.my_username, 'Server', None)
            msg.request(c_socket, 'QUIT')
            sys.exit('EXITED SYSTEM')

        # if there is a message to send, send it
        if out is not None:
            c_socket.send(out)
Example #10
0
def receive_msg_in(status, c_socket):
    try:
        while True:
            msg_in_header = c_socket.recv(base.header_len)
            header_len = len(msg_in_header)

            if not header_len:
                error = base.Error()
                error.broken_connection('SERVER')
                error.receive()
                sys.exit('EXITING')
                return False
            msg_in_len = int(msg_in_header.decode('utf-8').strip())

            if header_len > base.MSG_MAX:
                error = base.Error()
                error.msg_exceeds_len()
                error.receive()
                return False

            msg_in = c_socket.recv(msg_in_len).decode('utf-8')
            new_msg_in = json.loads(msg_in, object_hook=mm.json_msg_decoder)

            msg_status = new_msg_in.receive()
            if isinstance(new_msg_in, mm.ConnectionMessage):
                status = False
            elif isinstance(new_msg_in, mm.JoinMessage):
                if msg_status != 0:
                    print(
                        f'CLIENT ERROR, client server mismatch could not add {new_msg_in.sender} to {new_msg_in.data}')
                status = False
            elif isinstance(new_msg_in, mm.CreateRoomMessage):
                if msg_status != 1:
                    print(f'CLIENT ERROR: client server mismatch could not add {new_msg_in.data}')
                status = False
            elif isinstance(new_msg_in, base.Error):
                if msg_status == 3:
                    print(f'FATAL ERROR from Server EXITING')
                    sys.exit()
                status = True
            elif isinstance(new_msg_in, mm.ChatMessage):
                if msg_status == 0:
                    print("CLIENT ERROR: reading in chat message failed, check with Server admin")
                status = False
            elif isinstance(new_msg_in, mm.LeaveMessage):
                if msg_status != 1:
                    print(
                        f'CLIENT ERROR, client server mismatch could not remove {new_msg_in.sender}'
                        f'from {new_msg_in.data}')
                status = False
            else:
                print(f"{new_msg_in['sender']} >> {new_msg_in['type']} {new_msg_in['data']}")
    except IOError as e:
        if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:
            print('READ ERROR: could not read in from', str(e))
            sys.exit('EXITING')
        if status:
            return False
        else:
            return True

    return status