Modify the server and webclient to allow for timestamps and the room that the message came from.

This commit is contained in:
Charles Descamps 2025-03-28 19:59:13 -07:00
parent 21820453bd
commit 66202e154b
2 changed files with 25 additions and 7 deletions

View file

@ -7,6 +7,7 @@ import threading
from flask import Flask, request, jsonify
from flask_socketio import SocketIO, emit, join_room, leave_room
from flask_cors import CORS
from datetime import datetime # Import for timestamps
# Flask app for REST API and WebSocket
app = Flask(__name__)
@ -74,16 +75,24 @@ def get_client_uuid(client_socket, uuid_dict):
def handle_message(username, chat_room, message):
"""Store the message in history and broadcast it to all clients."""
# Add a timestamp to the message
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# Store the message in the chat room's history
if chat_room not in message_history:
message_history[chat_room] = []
message_history[chat_room].append(f"{username}: {message}")
message_history[chat_room].append(f"[{timestamp}] {username}: {message}")
# Broadcast the message to WebSocket clients in the chat room
socketio.emit('message', {'username': username, 'message': message}, room=chat_room)
socketio.emit('message', {
'username': username,
'message': message,
'timestamp': timestamp,
'chat_room': chat_room
}, room=chat_room)
# Broadcast the message to socket-based clients in the chat room
send_message = f"{username} >> {message}".encode('utf-8')
send_message = f"[{timestamp}] {username} >> {message}".encode('utf-8')
for client_sock in socket_list:
if client_sock != server_socket and chat_rooms.get(client_sock) == chat_room:
client_sock.send(send_message)
@ -134,6 +143,7 @@ def handle_command(username, chat_room, command, sock=None):
else:
target_username = parts[1]
dm_message = parts[2]
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
target_sock = None
for s, info in client_info.items():
if info.get("username") == target_username:
@ -141,11 +151,16 @@ def handle_command(username, chat_room, command, sock=None):
break
if target_sock:
sender_username = username
target_sock.send(f"DM from {sender_username}: {dm_message}\n".encode('utf-8'))
target_sock.send(f"[{timestamp}] DM from {sender_username}: {dm_message}\n".encode('utf-8'))
if sock:
sock.send(b"\nDirect message sent.\n")
sock.send(f"[{timestamp}] Direct message sent.\n".encode('utf-8'))
else:
socketio.emit('message', {'username': 'Server', 'message': "Direct message sent."}, room=chat_room)
socketio.emit('message', {
'username': sender_username,
'message': dm_message,
'timestamp': timestamp,
'chat_room': 'Direct Message'
}, room=chat_room)
else:
error_message = "User not found."
if sock:
@ -215,6 +230,7 @@ def get_history():
if chat_room not in message_history:
return jsonify({"messages": []}) # Return an empty list if no history exists
# Return the full message history with timestamps
return jsonify({"messages": message_history[chat_room]})
# WebSocket event handlers

View file

@ -197,7 +197,9 @@
// Listen for messages from the server
socket.on('message', (data) => {
const messageElement = document.createElement('div');
messageElement.textContent = `${data.username || 'Server'}: ${data.message}`;
const timestamp = data.timestamp ? `[${data.timestamp}]` : '';
const chatRoomInfo = data.chat_room ? `(${data.chat_room})` : '';
messageElement.textContent = `${timestamp} ${data.username || 'Server'} ${chatRoomInfo}: ${data.message}`;
chatDiv.appendChild(messageElement);
chatDiv.scrollTop = chatDiv.scrollHeight; // Auto-scroll to the bottom
});