From eaf9381bcab7ff1e17a3776dea2b746fb4a5a777 Mon Sep 17 00:00:00 2001 From: Russell Schmidt Date: Thu, 3 Jul 2025 12:23:16 -0500 Subject: [PATCH] Refactor message saving Add common function for saving a message to history, removing some duplicate code and making traceroutes add timestamps like other messages do. --- contact/message_handlers/rx_handler.py | 41 ++++++-------------------- contact/message_handlers/tx_handler.py | 41 +++++--------------------- contact/utilities/utils.py | 29 ++++++++++++++++++ 3 files changed, 45 insertions(+), 66 deletions(-) diff --git a/contact/message_handlers/rx_handler.py b/contact/message_handlers/rx_handler.py index 32bafe2..afdea71 100644 --- a/contact/message_handlers/rx_handler.py +++ b/contact/message_handlers/rx_handler.py @@ -3,11 +3,12 @@ import os import platform import shutil import subprocess -import time -from datetime import datetime from typing import Any, Dict -from contact.utilities.utils import refresh_node_list +from contact.utilities.utils import ( + refresh_node_list, + add_new_message, +) from contact.ui.contact_ui import ( draw_packetlog_win, draw_node_list, @@ -121,7 +122,9 @@ def on_receive(packet: Dict[str, Any], interface: Any) -> None: channel_number = ui_state.channel_list.index(packet["from"]) - if ui_state.channel_list[channel_number] != ui_state.channel_list[ui_state.selected_channel]: + channel_id = ui_state.channel_list[channel_number] + + if channel_id != ui_state.channel_list[ui_state.selected_channel]: add_notification(channel_number) refresh_channels = True else: @@ -131,40 +134,14 @@ def on_receive(packet: Dict[str, Any], interface: Any) -> None: message_from_id = packet["from"] message_from_string = get_name_from_database(message_from_id, type="short") + ":" - if ui_state.channel_list[channel_number] not in ui_state.all_messages: - ui_state.all_messages[ui_state.channel_list[channel_number]] = [] - - # Timestamp handling - current_timestamp = time.time() - current_hour = datetime.fromtimestamp(current_timestamp).strftime("%Y-%m-%d %H:00") - - # Retrieve the last timestamp if available - channel_messages = ui_state.all_messages[ui_state.channel_list[channel_number]] - if channel_messages: - # Check the last entry for a timestamp - for entry in reversed(channel_messages): - if entry[0].startswith("--"): - last_hour = entry[0].strip("- ").strip() - break - else: - last_hour = None - else: - last_hour = None - - # Add a new timestamp if it's a new hour - if last_hour != current_hour: - ui_state.all_messages[ui_state.channel_list[channel_number]].append((f"-- {current_hour} --", "")) - - ui_state.all_messages[ui_state.channel_list[channel_number]].append( - (f"{config.message_prefix} {message_from_string} ", message_string) - ) + add_new_message(channel_id, f"{config.message_prefix} {message_from_string} ", message_string) if refresh_channels: draw_channel_list() if refresh_messages: draw_messages_window(True) - save_message_to_db(ui_state.channel_list[channel_number], message_from_id, message_string) + save_message_to_db(channel_id, message_from_id, message_string) except KeyError as e: logging.error(f"Error processing packet: {e}") diff --git a/contact/message_handlers/tx_handler.py b/contact/message_handlers/tx_handler.py index 72b7f36..ac1dd19 100644 --- a/contact/message_handlers/tx_handler.py +++ b/contact/message_handlers/tx_handler.py @@ -1,4 +1,3 @@ -from datetime import datetime from typing import Any, Dict import google.protobuf.json_format @@ -16,6 +15,8 @@ import contact.ui.default_config as config from contact.utilities.singleton import ui_state, interface_state +from contact.utilities.utils import add_new_message + ack_naks: Dict[str, Dict[str, Any]] = {} # requestId -> {channel, messageIndex, timestamp} @@ -146,8 +147,9 @@ def on_response_traceroute(packet: Dict[str, Any]) -> None: update_node_info_in_db(packet["from"], chat_archived=False) channel_number = ui_state.channel_list.index(packet["from"]) + channel_id = ui_state.channel_list[channel_number] - if ui_state.channel_list[channel_number] == ui_state.channel_list[ui_state.selected_channel]: + if channel_id == ui_state.channel_list[ui_state.selected_channel]: refresh_messages = True else: add_notification(channel_number) @@ -155,18 +157,14 @@ def on_response_traceroute(packet: Dict[str, Any]) -> None: message_from_string = get_name_from_database(packet["from"], type="short") + ":\n" - if ui_state.channel_list[channel_number] not in ui_state.all_messages: - ui_state.all_messages[ui_state.channel_list[channel_number]] = [] - ui_state.all_messages[ui_state.channel_list[channel_number]].append( - (f"{config.message_prefix} {message_from_string}", msg_str) - ) + add_new_message(channel_id, f"{config.message_prefix} {message_from_string}", msg_str) if refresh_channels: draw_channel_list() if refresh_messages: draw_messages_window(True) - save_message_to_db(ui_state.channel_list[channel_number], packet["from"], msg_str) + save_message_to_db(channel_id, packet["from"], msg_str) def send_message(message: str, destination: int = BROADCAST_NUM, channel: int = 0) -> None: """ @@ -190,32 +188,7 @@ def send_message(message: str, destination: int = BROADCAST_NUM, channel: int = channelIndex=send_on_channel, ) - # Add sent message to the messages dictionary - if channel_id not in ui_state.all_messages: - ui_state.all_messages[channel_id] = [] - - # Handle timestamp logic - current_timestamp = int(datetime.now().timestamp()) # Get current timestamp - current_hour = datetime.fromtimestamp(current_timestamp).strftime("%Y-%m-%d %H:00") - - # Retrieve the last timestamp if available - channel_messages = ui_state.all_messages[channel_id] - if channel_messages: - # Check the last entry for a timestamp - for entry in reversed(channel_messages): - if entry[0].startswith("--"): - last_hour = entry[0].strip("- ").strip() - break - else: - last_hour = None - else: - last_hour = None - - # Add a new timestamp if it's a new hour - if last_hour != current_hour: - ui_state.all_messages[channel_id].append((f"-- {current_hour} --", "")) - - ui_state.all_messages[channel_id].append((config.sent_message_prefix + config.ack_unknown_str + ": ", message)) + add_new_message(channel_id, config.sent_message_prefix + config.ack_unknown_str + ": ", message) timestamp = save_message_to_db(channel_id, myid, message) diff --git a/contact/utilities/utils.py b/contact/utilities/utils.py index 83fab87..165b984 100644 --- a/contact/utilities/utils.py +++ b/contact/utilities/utils.py @@ -1,4 +1,5 @@ import datetime +import time from meshtastic.protobuf import config_pb2 import contact.ui.default_config as config @@ -134,3 +135,31 @@ def get_time_ago(timestamp): if unit != "s": return f"{value} {unit} ago" return "now" + +def add_new_message(channel_id, prefix, message): + if channel_id not in ui_state.all_messages: + ui_state.all_messages[channel_id] = [] + + # Timestamp handling + current_timestamp = time.time() + current_hour = datetime.datetime.fromtimestamp(current_timestamp).strftime("%Y-%m-%d %H:00") + + # Retrieve the last timestamp if available + channel_messages = ui_state.all_messages[channel_id] + if channel_messages: + # Check the last entry for a timestamp + for entry in reversed(channel_messages): + if entry[0].startswith("--"): + last_hour = entry[0].strip("- ").strip() + break + else: + last_hour = None + else: + last_hour = None + + # Add a new timestamp if it's a new hour + if last_hour != current_hour: + ui_state.all_messages[channel_id].append((f"-- {current_hour} --", "")) + + # Add the message + ui_state.all_messages[channel_id].append((prefix,message))