示例#1
0
def delete_message_item_selected_callback(messages_list: QListWidget,
                                          message_item):
    # that's ...
    dialogs_list = messages_list \
        .parentWidget() \
        .parentWidget() \
        .parentWidget() \
        .parentWidget() \
        .dialogs_list_frame \
        .dialogs_list
    dialog: DialogItemWidget = dialogs_list.currentItem()

    message_item_widget = messages_list.itemWidget(message_item)
    confirmation_dialog = DeleteMsgMessageBox(
        message_item_widget.message.mine,
        dialog.nickname if len(dialog.nickname) else None)

    result = confirmation_dialog.exec_()

    if result[0] == QMessageBox.Ok:
        delete_message(dialog.peer_id, message_item_widget.message.message_id)
        messages_list.takeItem(messages_list.row(message_item))
        if result[1]:
            delete_message_msg = Message(
                message_id=message_item_widget.message.message_id, timestamp=0)
            client_base.send_message(
                dialog.peer_id,
                Packet(action=DeleteMessageAction(),
                       message=delete_message_msg))
示例#2
0
 def from_json_obj(json_obj):
     packet = Packet(
         action=Action.from_json_obj(json_obj=json_obj["action"]),
         message=Message.from_json_obj(json_obj=json_obj["message"]))
     if json_obj["data"]:
         packet.data = Data.from_json_obj(json_obj=json_obj["data"])
     return packet
示例#3
0
def get_messages(peer_id):
    messages = SQLManager.get_instance(DB_MESSAGING).select_all(
        f"messages_{peer_id}")
    res = list()
    for msg in messages:
        res.append((Message(message_id=msg[0],
                            timestamp=msg[1],
                            text=msg[2],
                            mine=msg[3] == 1), bool(msg[4]), msg[5], msg[6]))

    return res
示例#4
0
def server_connect(remote_host: str,
                   remote_port: int,
                   peer_id_override: str = None) -> tuple:
    if len(peers.keys()) == 1024:
        return "Reached maximum connections limit", None

    address = (remote_host, remote_port)

    if address in sockets.keys():
        connection, connected = sockets[address]["connection"], sockets[
            address]["used"]
        if connected:
            return "Already connected to {}:{}".format(address[0],
                                                       address[1]), None
        sockets[address]["used"] = True
    else:
        connection = socket.socket()
        try:
            connection.connect(address)
        except ConnectionRefusedError:
            return "Server is offline", None
        except socket.gaierror as e:
            return str(e), None
        connection.settimeout(30)
        sockets[address] = {"connection": connection, "used": True}

    peer = Server(remote_host, remote_port)

    if peer_id_override:
        peer.peer_id = peer_id_override

    incoming_message_thread = threading.Thread(
        target=server_new_message_listener, args=[peer, connection])
    incoming_message_thread.setDaemon(True)

    peers[peer.peer_id] = {
        "peer": peer,
        "thread": incoming_message_thread,
        "socket": connection
    }

    incoming_message_thread.start()

    send_message(peer.peer_id, Packet(action=ConnectAction(),
                                      message=Message()))
    print('Connected to server')
    return None, peer
示例#5
0
def send_button_clicked_callback(widget, peer_id):
    if peer_id not in client_base.peers.keys():
        return

    message_text = full_strip(widget.message_input.toPlainText())
    widget.message_input.clear()
    if not len(message_text):
        return

    messages_list = widget.parentWidget().parentWidget().messages_list
    message = Message(text=message_text, mine=True)
    save_message(peer_id, message, "", from_nickname=client_base.nickname)
    message_item_widget = MessageItemWidget(message, "", client_base.nickname)
    item = QListWidgetItem()
    item.setSizeHint(message_item_widget.sizeHint())
    messages_list.addItem(item)
    messages_list.setItemWidget(item, message_item_widget)
    messages_list.scrollToBottom()
    msg_copy = copy.deepcopy(message)
    msg_copy.mine = False
    client_base.send_message(
        peer_id, Packet(action=NewMessageAction(), message=msg_copy))
示例#6
0
def edit_message_item_selected_callback(opened_dialog: QWidget,
                                        message_item: MessageItemWidget):
    old_message: Message = message_item.message
    text_to_edit = old_message.text

    new_text, ok = QInputDialog.getText(opened_dialog,
                                        "New Text",
                                        'Edit message text',
                                        text=text_to_edit)

    if ok and new_text != text_to_edit:
        dialog = opened_dialog.parentWidget().parentWidget(
        ).dialogs_list_frame.dialogs_list.currentItem()
        current_peer_id = dialog.peer_id
        message_item.message.text = new_text
        message_item.init_ui()
        new_message = Message(old_message.message_id, old_message.timestamp,
                              new_text, old_message.attachments, True)
        msg_copy = copy.deepcopy(new_message)
        msg_copy.mine = False
        packet = Packet(action=EditMessageAction(), message=msg_copy)
        client_base.send_message(current_peer_id, packet)
        message_item.message = new_message
        edit_message(current_peer_id, new_message)
示例#7
0
def delete_dialog_callback(peer_id: str, host: str, port: int):
    client_base.send_message(
        peer_id, Packet(action=DisconnectAction(), message=Message()))
    delete_dialog(peer_id)
    client_base.disconnect(Peer(host, port, peer_id))
示例#8
0
def new_message_callback(packet: Packet, peer: Peer, window):
    messages_list: QListWidget = window.centralWidget(
    ).opened_dialog_frame.messages_list

    action = packet.action.action  # yes, I know
    peer_id = packet.data.content.get(
        "from_peer") if packet.data and packet.data.content.get(
            "from_peer", None) else peer.peer_id
    previous_peer_id = messages_list.itemWidget(
        messages_list.item(
            messages_list.count() -
            1)).from_peer_id if messages_list.count() > 0 else None

    if action == NewMessageAction().action:
        message_item_widget = MessageItemWidget(
            packet.message,
            peer_id,
            peer.nickname if type(peer) is Client else "",
            previous_peer_id=previous_peer_id)
        item = QListWidgetItem()
        item.setSizeHint(message_item_widget.sizeHint())
        messages_list.addItem(item)
        messages_list.setItemWidget(item, message_item_widget)
        messages_list.scrollToBottom()
        save_message(peer.peer_id, packet.message, peer_id,
                     peer.nickname if type(peer) is Client else "")
    elif action == DeleteMessageAction().action:
        delete_message(peer.peer_id, packet.message.message_id)
        for index in range(messages_list.count()):
            message_item = messages_list.item(index)
            message_item_widget: MessageItemWidget = messages_list.itemWidget(
                message_item)
            if message_item_widget.message.message_id == packet.message.message_id:
                messages_list.takeItem(messages_list.row(message_item))
                break
    elif action == EditMessageAction().action:
        edit_message(peer.peer_id, packet.message)
        for index in range(messages_list.count()):
            message_item = messages_list.item(index)
            message_item_widget: MessageItemWidget = messages_list.itemWidget(
                message_item)
            if message_item_widget.message.message_id == packet.message.message_id:
                message_item_widget.init_ui()
                break
    elif action == PeerInfoAction().action:
        nickname = packet.data.content["nickname"]
        port = packet.data.content["port"]
        update_dialog_info(nickname, port, peer_id)
        dialog_widget: DialogItemWidget = window.centralWidget(
        ).dialogs_list_frame.dialogs_list.currentItem()
        dialog_widget.nickname = nickname
        dialog_widget.port = port
        dialog_widget.update_ui()
        messages_list.viewport().setFocus()
        if packet.data.content["request"]:
            client_base.send_message(
                dialog_widget.peer_id,
                Packet(message=Message(text=""),
                       action=PeerInfoAction(),
                       data=Data(
                           content={
                               "nickname": client_base.nickname,
                               "port": client_base.local_port,
                               "request": False
                           })))
    elif action == ServiceAction().action:
        message_item_widget = MessageItemWidget(packet.message, peer.peer_id,
                                                "", True)
        item = QListWidgetItem()
        item.setSizeHint(message_item_widget.sizeHint())
        messages_list.addItem(item)
        messages_list.setItemWidget(item, message_item_widget)
        messages_list.scrollToBottom()
        save_message(peer.peer_id, packet.message, peer.peer_id, True)
    elif action == DisconnectAction().action:
        pass
        # TODO peer has disconnected
    elif action == ConnectAction().action:
        if packet.data:  # indicates that it's just reconnect
            return
        # pretend that we are server
        client_base.send_message(
            peer_id,
            Packet(action=ServiceAction(),
                   message=Message(text="Wrong button, buddy :)")))
        client_base.peers[peer_id]["socket"].close()
        client_base.peers.pop(peer_id)
        sleep(0.5)
        dialogs_list = window.centralWidget().dialogs_list_frame.dialogs_list
        dialogs_list.takeItem(dialogs_list.row(dialogs_list.currentItem()))
        delete_dialog(peer.peer_id)