Skip to content

Commit f93e87c

Browse files
committed
todos
1 parent ca8a79f commit f93e87c

File tree

3 files changed

+126
-57
lines changed

3 files changed

+126
-57
lines changed

client/src/routes/chat.tsx

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,13 @@ export default function Chat() {
1414
setError("Please enter a name and room code.");
1515
return;
1616
}
17+
// TODO: use ChatRoom model, you will need to call an API endpoint here
18+
// TODO: create an API endpoint in chat.py
19+
// check that the code is existing in the database (if not error)
20+
// if code is existing, check that the room is active (if not error)
21+
// if room is active, check that the room is not full (if full error)
22+
// if user is added to room, navigate to the room
23+
// navigate to "/room/${code}" also change in App.tsx
1724
navigate(`/room?name=${encodeURIComponent(name)}&code=${encodeURIComponent(code)}`);
1825
};
1926

@@ -23,6 +30,12 @@ export default function Chat() {
2330
setError("Please enter a name.");
2431
return;
2532
}
33+
// TODO: call api endpoint / create it
34+
// need to check that randomly generated code does not exist in datbase
35+
// if it does, generate a new one until it does not exist in the database
36+
// if it does not exist, create the room in the database
37+
// if room is created, navigate to the room
38+
// navigate to "/room/${code}" also change in App.tsx
2639
const newCode = Math.random().toString(36).substring(2, 6).toUpperCase();
2740
navigate(`/room?name=${encodeURIComponent(name)}&code=${encodeURIComponent(newCode)}`);
2841
};

client/src/routes/chatRoom.tsx

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,14 @@ import io from "socket.io-client";
44
import styles from "./chat.module.css";
55

66

7-
const socket = io("http://127.0.0.1:3001", { transports: ["websocket"] });
7+
const socket = io("http://127.0.0.1:3001", { transports: ["polling", "websocket"] });
88

99
export default function ChatRoom() {
1010
const location = useLocation();
1111
const navigate = useNavigate();
1212
const queryParams = new URLSearchParams(location.search);
1313
const name = queryParams.get("name") || "";
14+
// TODO: get code from the url getParams
1415
const code = queryParams.get("code") || "";
1516

1617
const [messages, setMessages] = useState<{ name: string; message: string }[]>([]);
@@ -45,12 +46,14 @@ export default function ChatRoom() {
4546
<div className={styles.content}>
4647
<div className={styles.messageBox}>
4748
<h2>Chat Room: {code}</h2>
49+
{/* add a message that says chat not saved, if they refresh ask are you sure you will lose your chat msg */}
4850
<div className={styles.messages}>
4951
{/* Temporary hardcoded message for debugging */}
5052
<div className={styles.text}>
5153
<span>
5254
<strong>Test User</strong>: This is a test message
5355
</span>
56+
{/* TODO: check out date problem */}
5457
<span className={styles.muted}>{new Date().toLocaleString()}</span>
5558
</div>
5659

server/controllers/chat.py

Lines changed: 109 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,14 @@
1-
from server.config import (
2-
FRONTEND_URL
1+
from server.config import FRONTEND_URL
2+
from flask import (
3+
current_app as app,
4+
Flask,
5+
url_for,
6+
redirect,
7+
session,
8+
request,
9+
send_file,
10+
jsonify,
311
)
4-
from flask import current_app as app, Flask, url_for, redirect, session, request, send_file, jsonify
512
from flask_socketio import emit, join_room, leave_room, send, SocketIO
613
from server import db, socketio
714
from authlib.integrations.flask_client import OAuth
@@ -16,76 +23,122 @@
1623
chat = APIBlueprint("chat", __name__, url_prefix="/chat")
1724

1825

19-
2026
rooms = {}
2127

28+
2229
def generate_unique_code(length):
2330
while True:
2431
code = ""
2532
for _ in range(length):
2633
code += random.choice(ascii_uppercase)
27-
34+
2835
if code not in rooms:
2936
break
30-
37+
3138
return code
3239

33-
@chat.route("/", methods=["POST", "GET"])
34-
def home():
35-
session.clear()
36-
if request.method == "POST":
37-
name = request.form.get("name")
38-
code = request.form.get("code")
39-
join = request.form.get("join", False)
40-
create = request.form.get("create", False)
41-
42-
if not name:
43-
return redirect(FRONTEND_URL)
44-
45-
# return render_template("home.html", error="Please enter a name.", code=code, name=name)
46-
47-
if join is not False and not code:
48-
return redirect(FRONTEND_URL)
49-
50-
# return render_template("home.html", error="Please enter a room code.", code=code, name=name)
51-
52-
room = code
53-
if create is not False:
54-
room = generate_unique_code(4)
55-
rooms[room] = {"members": 0, "messages": []}
56-
elif code not in rooms:
57-
return redirect(FRONTEND_URL)
58-
59-
# return render_template("home.html", error="Room does not exist.", code=code, name=name)
60-
61-
session["room"] = room
62-
session["name"] = name
63-
return redirect(url_for("room"))
64-
65-
66-
@chat.route("/room")
67-
def room():
68-
room = session.get("room")
69-
if room is None or session.get("name") is None or room not in rooms:
70-
return redirect(url_for("home"))
7140

72-
redirect(url_for("room"))
73-
# return render_template("room.html", code=room, messages=rooms[room]["messages"])
41+
# @chat.route("/", methods=["POST", "GET"])
42+
# def home():
43+
# session.clear()
44+
# if request.method == "POST":
45+
# name = request.form.get("name")
46+
# code = request.form.get("code")
47+
# join = request.form.get("join", False)
48+
# create = request.form.get("create", False)
49+
50+
# if not name:
51+
# return redirect(FRONTEND_URL)
52+
53+
# # return render_template("home.html", error="Please enter a name.", code=code, name=name)
54+
55+
# if join is not False and not code:
56+
# return redirect(FRONTEND_URL)
57+
58+
# # return render_template("home.html", error="Please enter a room code.", code=code, name=name)
59+
60+
# room = code
61+
# if create is not False:
62+
# room = generate_unique_code(4)
63+
# rooms[room] = {"members": 0, "messages": []}
64+
# elif code not in rooms:
65+
# return redirect(FRONTEND_URL)
66+
67+
# # return render_template("home.html", error="Room does not exist.", code=code, name=name)
7468

75-
@socketio.on("message") # TODO: MOVE THIS TO CHAT.PY
69+
# session["room"] = room
70+
# session["name"] = name
71+
# return redirect(url_for("room"))
72+
73+
74+
# @chat.route("/room")
75+
# def room():
76+
# room = session.get("room")
77+
# if room is None or session.get("name") is None or room not in rooms:
78+
# return redirect(url_for("home"))
79+
80+
# return redirect(url_for("room"))
81+
# # return render_template("room.html", code=room, messages=rooms[room]["messages"])
82+
83+
84+
@socketio.on("message") # TODO: MOVE THIS TO CHAT.PY
7685
def message(data):
7786
room = session.get("room")
7887
if room not in rooms:
79-
return
80-
81-
content = {
82-
"name": session.get("name"),
83-
"message": data["data"]
84-
}
88+
return
89+
90+
content = {"name": session.get("name"), "message": data["data"]}
8591
emit("message", content, to=room)
8692
rooms[room]["messages"].append(content)
8793
print(f"{session.get('name')} said: {data['data']}")
8894

95+
96+
@socketio.on("join")
97+
def handle_join(data):
98+
"""Handles when a user joins a chat room."""
99+
room = data.get("code") # Get room code from frontend
100+
name = data.get("name")
101+
102+
if not room or not name:
103+
return # Ignore invalid join requests
104+
105+
if room not in rooms:
106+
rooms[room] = {"members": 0, "messages": []}
107+
108+
join_room(room)
109+
rooms[room]["members"] += 1
110+
111+
# Notify others in the room
112+
emit(
113+
"message",
114+
{"name": "System", "message": f"{name} has joined the room."},
115+
to=room,
116+
)
117+
print(f"{name} joined room {room}")
118+
119+
120+
@socketio.on("leave")
121+
def handle_leave(data):
122+
"""Handles when a user leaves a chat room."""
123+
room = data.get("code") # Get room code from frontend
124+
name = data.get("name")
125+
126+
if not room or not name:
127+
return
128+
129+
leave_room(room)
130+
rooms[room]["members"] -= 1
131+
132+
# Remove room if empty
133+
if rooms[room]["members"] <= 0:
134+
del rooms[room]
135+
136+
emit(
137+
"message", {"name": "System", "message": f"{name} has left the room."}, to=room
138+
)
139+
print(f"{name} left room {room}")
140+
141+
89142
@socketio.on("connect")
90143
def connect(auth):
91144
print("client connected")
@@ -96,12 +149,13 @@ def connect(auth):
96149
if room not in rooms:
97150
leave_room(room)
98151
return
99-
152+
100153
join_room(room)
101154
emit("message", {"name": name, "message": "has entered the room"}, to=room)
102155
rooms[room]["members"] += 1
103156
print(f"{name} joined room {room}")
104157

158+
105159
@socketio.on("disconnect")
106160
def disconnect():
107161
room = session.get("room")
@@ -112,7 +166,6 @@ def disconnect():
112166
rooms[room]["members"] -= 1
113167
if rooms[room]["members"] <= 0:
114168
del rooms[room]
115-
169+
116170
emit("message", {"name": name, "message": "has left the room"}, to=room)
117171
print(f"{name} has left the room {room}")
118-

0 commit comments

Comments
 (0)