Add the send direct message route for the REST API.

This commit is contained in:
Charles Descamps 2025-03-28 20:42:38 -07:00
parent e12f8497f4
commit 20b2702fcf

View file

@ -248,6 +248,50 @@ def get_history():
# Return the full message history with timestamps # Return the full message history with timestamps
return jsonify({"messages": message_history[chat_room]}) return jsonify({"messages": message_history[chat_room]})
@app.route('/send_direct_message', methods=['POST'])
def send_direct_message():
"""Send a direct message to a specific user."""
data = request.json
sender_username = data.get('sender_username')
target_username = data.get('target_username')
message = data.get('message')
if not sender_username or not target_username or not message:
return jsonify({"error": "Sender username, target username, and message are required"}), 400
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# Check if the target is a socket-based client
target_sock = None
for s, info in client_info.items():
if not info.get("is_websocket") and info.get("username") == target_username:
target_sock = s
break
# Check if the target is a WebSocket client
target_websocket_sid = None
for sid, info in client_info.items():
if info.get("is_websocket") and info.get("username") == target_username:
target_websocket_sid = sid
break
if target_sock:
# Send the direct message to the socket-based client
target_sock.send(f"[{timestamp}] DM from {sender_username}: {message}\n".encode('utf-8'))
return jsonify({"status": "Direct message sent to socket-based client"}), 200
elif target_websocket_sid:
# Send the direct message to the WebSocket client
socketio.emit('message', {
'username': sender_username,
'message': message,
'timestamp': timestamp,
'chat_room': 'Direct Message'
}, to=target_websocket_sid)
return jsonify({"status": "Direct message sent to WebSocket client"}), 200
else:
# Target user not found
return jsonify({"error": "Target user not found"}), 404
# WebSocket event handlers # WebSocket event handlers
@socketio.on('connect') @socketio.on('connect')
def handle_connect(): def handle_connect():