Improved chat.py and created a temporary chat.html to be transferred to react later

This commit is contained in:
white
2025-01-24 17:02:56 +00:00
parent 8ec60b1c41
commit ae9cd96333
6 changed files with 311 additions and 37 deletions

View File

@@ -4,36 +4,10 @@ from database.database import Database
chat_bp = Blueprint("chat", __name__)
@chat_bp.route("/send_chat", methods=["POST"])
@login_required
def send_chat():
"""
Works with react, takes the chat entered by a logged in user and stores in database
"""
# <---------------------- ROUTES NEEDS TO BE CHANGED TO VIDEO OR DELETED AS DEEMED APPROPRIATE ---------------------->
# TODO: Add a route that deletes all chat logs when the stream is finished
# Take the message information from frontend
data = request.get_json()
chatter_id = data.get("chatter_id")
stream_id = data.get("stream_id")
message = data.get("message")
# Input validation - chatter is logged in, message is not empty, stream exists
if not all(chatter_id, message, stream_id):
return {"chat_sent": False}
# Save chat information to database so other users can see
db = Database()
cursor = db.create_connection()
cursor.execute("""
INSERT INTO chat (chatter_id, stream_id, message)
VALUES (?, ?, ?);""", (chatter_id, stream_id, message))
db.commit_data()
return {"chat_sent": True}
# <---------------------- ROUTE NEEDS TO BE CHANGED TO VIDEO OR DELETED AS DEEMED APPROPRIATE ---------------------->
@chat_bp.route("/chat/<int:stream_id>", methods=["GET"])
@chat_bp.route("/chat/<int:stream_id>")
def get_past_chat(stream_id):
"""
Returns a JSON object to be passed to the server.
@@ -51,11 +25,11 @@ def get_past_chat(stream_id):
all_chats = cursor.execute("""
SELECT *
FROM (
SELECT chatter_id, message, time_sent
FROM chat
WHERE stream_id = ?
ORDER BY time_sent DESC
LIMIT 50
SELECT chatter_id, message, time_sent
FROM chat
WHERE stream_id = ?
ORDER BY time_sent DESC
LIMIT 50
)
ORDER BY time_sent ASC;""", (stream_id,)).fetchall()
db.close_connection()
@@ -64,14 +38,48 @@ def get_past_chat(stream_id):
chat_history = [{"chatter_id": chat[0], "message": chat[1], "time_sent": chat[2]} for chat in all_chats]
# Pass the chat history to the proxy
return jsonify(chat_history)
return jsonify({"chat_history": chat_history}), 200
@chat_bp.route("/send_chat", methods=["POST"])
@login_required
def send_chat():
"""
Works with react, takes the chat entered by a logged in user and stores in database
"""
# Take the message information from frontend
data = request.get_json()
chatter_id = data.get("chatter_id")
stream_id = data.get("stream_id")
message = data.get("message")
# Input validation - chatter is logged in, message is not empty, stream exists
if not all([chatter_id, message, stream_id]):
return jsonify({"chat_sent": False}), 400
# Save chat information to database so other users can see
db = Database()
cursor = db.create_connection()
cursor.execute("""
INSERT INTO chat (chatter_id, stream_id, message)
VALUES (?, ?, ?);""", (chatter_id, stream_id, message))
db.commit_data()
db.close_connection()
return jsonify({"chat_sent": True}), 200
@chat_bp.route("/load_new_chat/<int:stream_id>", methods=["GET"])
def get_recent_chat(stream_id):
"""
Fetch new chat messages on a stream a user has already loaded in to.
"""
# Get the last received chat to avoid repeating old chats
last_received = request.args.get("last_received") # last_received is a time stamp
if not last_received:
return jsonify({"error": "last_received timestamp required"}), 400
# Get the most recent chats from the database
db = Database()
@@ -86,4 +94,5 @@ def get_recent_chat(stream_id):
db.close_connection()
# Send the new chats to frontend
return jsonify(new_chats)
chat_data = [{"chatter_id": chat[0], "message": chat[1], "time_sent": chat[2]} for chat in new_chats]
return jsonify(chat_data), 200

View File

@@ -0,0 +1,83 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat Interface</title>
<script>
let last_received = "";
const stream_id = "{{ stream_id }}";
function add_to_chat(data){
const chat_container = document.getElementById("chat_container");
data.forEach(element => {
const div = document.createElement("div");
div.textContent = `${element.time_sent} ${element.chatter_id}: ${element.message}`;
chat_container.appendChild(div);
last_received = element.time_sent;
});
}
function loadPrevChat() {
const init_chat_logs = JSON.parse('{{ chat_history | tojson }}');
add_to_chat(init_chat_logs);
}
function sendChat(){
// Get the chat message sent by user
const chat_message = document.getElementById("messageInput").value;
document.getElementById("messageInput").value = "";
// Pass the chat message to python to store in chat log db
const data = {"chatter_id": "{{ chatter_id }}", "stream_id": "{{ stream_id }}", "message":chat_message};
const json_data = JSON.stringify(data);
fetch("/send_chat", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: json_data
})
// Check if message has been sent
.then(response => {
if (response.ok){
getRecentChats();
}
})
}
function getRecentChats(){
// Let the backend know the most recent chat message the user has
fetch(`/recent_chat/${stream_id}?last_received=${last_received}`)
.then(response => {
if (!response.ok){
throw new Error(`Failed to fetch chats`)
}
return response.json();
})
.then(data => {
add_to_chat(data);
})
.catch(error => {
console.error("Error fetching recent chats:", error);
});
}
window.addEventListener('DOMContentLoaded', loadPrevChat);
</script>
</head>
<body>
<h1>Chat for Stream #{{ stream_id }}</h1>
<div id="chat_container" style="max-height: 400px; overflow-y: auto;"></div>
<input type="text" id="messageInput" placeholder="Type a message" />
<button onclick="sendChat()">Send</button>
</body>
</html>

Binary file not shown.

View File

@@ -52,7 +52,7 @@ CREATE TABLE follows
DROP TABLE IF EXISTS chat;
CREATE TABLE chat
(
message_id INTEGER,
message_id INTEGER PRIMARY KEY AUTOINCREMENT,
stream_id INTEGER NOT NULL,
chatter_id VARCHAR(50) NOT NULL,
message VARCHAR(256) NOT NULL,