Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request
|
| 2 |
+
from fastapi.responses import HTMLResponse
|
| 3 |
+
from fastapi.templating import Jinja2Templates
|
| 4 |
+
import uuid
|
| 5 |
+
import json
|
| 6 |
+
|
| 7 |
+
app = FastAPI(title="FastAPI Chat")
|
| 8 |
+
templates = Jinja2Templates(directory="templates")
|
| 9 |
+
|
| 10 |
+
# Store active rooms: {room_id: [websocket_connections]}
|
| 11 |
+
active_rooms = {}
|
| 12 |
+
|
| 13 |
+
@app.get("/", response_class=HTMLResponse)
|
| 14 |
+
async def home(request: Request):
|
| 15 |
+
return templates.TemplateResponse("index.html", {"request": request})
|
| 16 |
+
|
| 17 |
+
@app.post("/create-room")
|
| 18 |
+
async def create_room():
|
| 19 |
+
"""Create a new chat room and return its ID"""
|
| 20 |
+
room_id = str(uuid.uuid4())[:8] # Generate short, unique room ID
|
| 21 |
+
active_rooms[room_id] = []
|
| 22 |
+
return {"room_id": room_id, "success": True}
|
| 23 |
+
|
| 24 |
+
@app.websocket("/ws/{room_id}")
|
| 25 |
+
async def websocket_endpoint(websocket: WebSocket, room_id: str):
|
| 26 |
+
"""Handle WebSocket connections for a specific room"""
|
| 27 |
+
if room_id not in active_rooms:
|
| 28 |
+
await websocket.close(code=1008, reason="Room not found")
|
| 29 |
+
return
|
| 30 |
+
|
| 31 |
+
await websocket.accept()
|
| 32 |
+
active_rooms[room_id].append(websocket)
|
| 33 |
+
|
| 34 |
+
# Notify all users about the new user
|
| 35 |
+
user_count = len(active_rooms[room_id])
|
| 36 |
+
system_message = json.dumps({
|
| 37 |
+
"type": "system",
|
| 38 |
+
"message": f"User joined. Total users: {user_count}",
|
| 39 |
+
"userCount": user_count
|
| 40 |
+
})
|
| 41 |
+
|
| 42 |
+
for connection in active_rooms[room_id]:
|
| 43 |
+
try:
|
| 44 |
+
await connection.send_text(system_message)
|
| 45 |
+
except:
|
| 46 |
+
pass
|
| 47 |
+
|
| 48 |
+
try:
|
| 49 |
+
while True:
|
| 50 |
+
# Receive message from client
|
| 51 |
+
data = await websocket.receive_text()
|
| 52 |
+
message_data = json.loads(data)
|
| 53 |
+
|
| 54 |
+
# Broadcast to all users in the room
|
| 55 |
+
broadcast_message = json.dumps({
|
| 56 |
+
"type": "message",
|
| 57 |
+
"username": message_data.get("username", "Anonymous"),
|
| 58 |
+
"text": message_data.get("text", "")
|
| 59 |
+
})
|
| 60 |
+
|
| 61 |
+
for connection in active_rooms[room_id]:
|
| 62 |
+
try:
|
| 63 |
+
await connection.send_text(broadcast_message)
|
| 64 |
+
except:
|
| 65 |
+
pass
|
| 66 |
+
|
| 67 |
+
except WebSocketDisconnect:
|
| 68 |
+
# Remove disconnected user
|
| 69 |
+
if websocket in active_rooms[room_id]:
|
| 70 |
+
active_rooms[room_id].remove(websocket)
|
| 71 |
+
|
| 72 |
+
# Clean up empty rooms
|
| 73 |
+
if not active_rooms[room_id]:
|
| 74 |
+
del active_rooms[room_id]
|
| 75 |
+
else:
|
| 76 |
+
# Notify remaining users
|
| 77 |
+
user_count = len(active_rooms[room_id])
|
| 78 |
+
leave_message = json.dumps({
|
| 79 |
+
"type": "system",
|
| 80 |
+
"message": f"User left. Total users: {user_count}",
|
| 81 |
+
"userCount": user_count
|
| 82 |
+
})
|
| 83 |
+
for connection in active_rooms[room_id]:
|
| 84 |
+
try:
|
| 85 |
+
await connection.send_text(leave_message)
|
| 86 |
+
except:
|
| 87 |
+
pass
|