Added Websockets to chat

This commit is contained in:
white
2025-01-25 12:45:09 +00:00
parent a409e74992
commit f4aed8b0cc
4 changed files with 85 additions and 83 deletions

View File

@@ -1,4 +1,4 @@
from flask import Flask, jsonify
from flask import Flask
# from flask_wtf.csrf import CSRFProtect, generate_csrf
from flask_session import Session
from blueprints.utils import logged_in_user
@@ -30,8 +30,9 @@ def create_app():
from blueprints.stripe import stripe_bp
from blueprints.user import user_bp
from blueprints.streams import stream_bp
from blueprints.chat import chat_bp
from blueprints.chat import chat_bp, socketio
# Registering Blueprints
app.register_blueprint(auth_bp)
app.register_blueprint(main_bp)
app.register_blueprint(stripe_bp)
@@ -39,4 +40,7 @@ def create_app():
app.register_blueprint(stream_bp)
app.register_blueprint(chat_bp)
# Tell sockets where the initialisation app is
socketio.init_app(app, cors_allowed_origins="*")
return app

View File

@@ -1,12 +1,39 @@
from flask import Blueprint, request, jsonify
from flask import Blueprint, request, jsonify, session
from blueprints.utils import login_required
from database.database import Database
from flask_socketio import SocketIO, emit, join_room, leave_room
from datetime import datetime
chat_bp = Blueprint("chat", __name__)
socketio = SocketIO()
# <---------------------- 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
@socketio.on("connect")
def handle_connection():
print("Client Connected")
@socketio.on("join")
def handle_join(data):
"""
Allow a user to join the chat of the stream they are watching.
"""
stream_id = data.get("stream_id")
if stream_id:
join_room(stream_id)
emit("status", {"message": f"Welcome to the chat, stream_id: {stream_id}"}, room=stream_id)
@socketio.on("leave")
def handle_leave(data):
"""
Handle what happens when a user leaves the stream they are watching in regards to the chat.
"""
stream_id = data.get("stream_id")
if stream_id:
leave_room(stream_id)
emit("status", {"message": f"user left room {stream_id}"}, room=stream_id)
@chat_bp.route("/chat/<int:stream_id>")
def get_past_chat(stream_id):
"""
@@ -40,22 +67,21 @@ def get_past_chat(stream_id):
# Pass the chat history to the proxy
return jsonify({"chat_history": chat_history}), 200
@chat_bp.route("/send_chat", methods=["POST"])
@login_required
def send_chat():
@socketio.on("send_message")
def send_chat(data):
"""
Works with react, takes the chat entered by a logged in user and stores in database
Using WebSockets to send a chat message to the specified chat
"""
# Take the message information from frontend
data = request.get_json()
chatter_id = data.get("chatter_id")
chatter_id = data.get("chatter_id") # Need to change this to get session info
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
emit("error", {"error": "Unable to send a chat"}, broadcast=False)
return
# Save chat information to database so other users can see
db = Database()
@@ -66,33 +92,8 @@ def send_chat():
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()
cursor = db.create_connection()
# fetched in format: [(chatter_id, message, time_sent)]
new_chats = cursor.execute("""
SELECT chatter_id, message, time_sent
FROM chat
WHERE stream_id = ?
AND time_sent > ?;""", (stream_id, last_received)).fetchall()
db.close_connection()
# Send the new chats to frontend
chat_data = [{"chatter_id": chat[0], "message": chat[1], "time_sent": chat[2]} for chat in new_chats]
return jsonify(chat_data), 200
emit("new_message", {
"chatter_id":chatter_id,
"message":message,
"time_sent": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
}, room=stream_id)

View File

@@ -5,22 +5,37 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat Interface</title>
<script src="https://cdn.socket.io/4.5.4/socket.io.min.js"></script>
<script>
let last_received = "";
// Global constants
const socket = io("http://127.0.0.1:5000"); // TODO: Change this
const stream_id = "{{ stream_id }}";
const chatter_id = "{{ chatter_id }}";
function add_to_chat(data){
const chat_container = document.getElementById("chat_container");
console.log(data)
data.forEach(element => {
// Add each chat message to the chat box, one by one
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;
});
})
chat_container.scrollTop = chat_container.scrollHeight; // keeps you at the bottom of the chat
}
socket.on("connect", () => {
console.log("Socket Connection established!");
})
// Wait for a new message to be sent
socket.on("new_message", (data) => {
console.log("New message");
add_to_chat([data]);
});
function loadPrevChat() {
const init_chat_logs = JSON.parse('{{ chat_history | tojson }}');
add_to_chat(init_chat_logs);
@@ -28,48 +43,29 @@
}
function sendChat(){
// Get the chat message sent by user
const chat_message = document.getElementById("messageInput").value;
document.getElementById("messageInput").value = "";
// Get the chat message sent by user, if none, don't
const chat_message = document.getElementById("messageInput").value.trim();
if (!chat_message) return;
// 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);
document.getElementById("messageInput").value = ""; // clear the chat box
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);
// Send the message using sockets
socket.emit("send_message", {
chatter_id: chatter_id,
stream_id: stream_id,
message: chat_message
});
}
window.addEventListener('DOMContentLoaded', loadPrevChat);
window.addEventListener('DOMContentLoaded', () => {
socket.emit("join", {stream_id: stream_id});
loadPrevChat();
});
window.addEventListener("beforeunload", () => {
socket.emit("leave", {stream_id: stream_id});
});
</script>

View File

@@ -21,3 +21,4 @@ urllib3==2.3.0
Werkzeug==3.1.3
WTForms==3.2.1
Gunicorn==20.1.0
flask-socketio==5.5.1