From ebd6c1803296a28ae8030b11ace219d0898abf25 Mon Sep 17 00:00:00 2001 From: Yohann D'ANELLO Date: Mon, 21 Dec 2020 16:04:16 +0100 Subject: [PATCH] Ignore duplicate messages Signed-off-by: Yohann D'ANELLO --- squinnondation/hazel.py | 34 +++++++++++++++++++++++++++++++++- squinnondation/messages.py | 5 ++++- 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/squinnondation/hazel.py b/squinnondation/hazel.py index f72f31a..b01428d 100644 --- a/squinnondation/hazel.py +++ b/squinnondation/hazel.py @@ -1,6 +1,6 @@ # Copyright (C) 2020 by eichhornchen, ÿnérant # SPDX-License-Identifier: GPL-3.0-or-later - +from datetime import datetime from typing import Any, Tuple from ipaddress import IPv6Address from threading import Thread @@ -49,6 +49,7 @@ class Squirrel(Hazelnut): self.last_line = -1 self.history = [] + self.received_messages = dict() self.history_pad = curses.newpad(curses.LINES - 2, curses.COLS) self.input_pad = curses.newpad(1, curses.COLS) self.emoji_pad = curses.newpad(18, 12) @@ -252,6 +253,19 @@ class Squirrel(Hazelnut): if self.last_line == len(self.history) - 2: self.last_line += 1 + def receive_message_from(self, msg: str, sender_id: int, nonce: int) -> bool: + """ + This method is called by a DataTLV, sent by a real person. + This add the message in the history if not already done. + Returns True iff the message was not already received previously. + """ + if (sender_id, nonce) in self.received_messages: + return False + + self.add_message(msg) + self.received_messages[(sender_id, nonce)] = Message(msg, sender_id, nonce) + return True + def add_system_message(self, msg: str) -> None: """ Add a new system log message. @@ -457,3 +471,21 @@ class Worm(Thread): tlv.handle(self.squirrel, hazelnut) self.squirrel.refresh_history() self.squirrel.refresh_input() + + +class Message: + """ + This class symbolises the data sent by a real client, excluding system messages. + This is useful to check unicity or to save and load messages. + """ + content: str + # TODO: Replace the id by the good (potential) hazel + sender_id: int + nonce: int + created_at: datetime + + def __init__(self, content: str, sender_id: int, nonce: int, created_at: datetime = None): + self.content = content + self.sender_id = sender_id + self.nonce = nonce + self.created_at = created_at or datetime.now() diff --git a/squinnondation/messages.py b/squinnondation/messages.py index 8e49f85..7080e74 100644 --- a/squinnondation/messages.py +++ b/squinnondation/messages.py @@ -208,7 +208,10 @@ class DataTLV(TLV): TODO: Check that the tuple (sender_id, nonce) is unique to avoid duplicates. """ msg = self.data.decode('UTF-8') - squirrel.add_message(msg) + if not squirrel.receive_message_from(msg, self.sender_id, self.nonce): + # The message was already received + return + nickname_match = re.match("(.*): (.*)", msg) if nickname_match is None: squirrel.send_packet(sender, Packet.construct(WarningTLV.construct(