Update main.py
Browse files
main.py
CHANGED
|
@@ -1,14 +1,26 @@
|
|
| 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):
|
|
@@ -17,10 +29,42 @@ async def home(request: Request):
|
|
| 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]
|
| 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"""
|
|
@@ -47,15 +91,15 @@ async def websocket_endpoint(websocket: WebSocket, room_id: str):
|
|
| 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]:
|
|
@@ -65,15 +109,20 @@ async def websocket_endpoint(websocket: WebSocket, room_id: str):
|
|
| 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",
|
|
|
|
| 1 |
+
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request, UploadFile, File, HTTPException
|
| 2 |
+
from fastapi.responses import HTMLResponse, FileResponse
|
| 3 |
+
from fastapi.staticfiles import StaticFiles
|
| 4 |
from fastapi.templating import Jinja2Templates
|
| 5 |
import uuid
|
| 6 |
import json
|
| 7 |
+
import os
|
| 8 |
+
from pathlib import Path
|
| 9 |
|
| 10 |
app = FastAPI(title="FastAPI Chat")
|
| 11 |
templates = Jinja2Templates(directory="templates")
|
| 12 |
|
| 13 |
+
# Create uploads directory
|
| 14 |
+
UPLOAD_DIR = Path("uploads")
|
| 15 |
+
UPLOAD_DIR.mkdir(exist_ok=True)
|
| 16 |
+
|
| 17 |
+
# Mount static files
|
| 18 |
+
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
|
| 19 |
+
|
| 20 |
# Store active rooms: {room_id: [websocket_connections]}
|
| 21 |
active_rooms = {}
|
| 22 |
+
# Store uploaded files info: {room_id: [{filename, original_name, file_type}]}
|
| 23 |
+
room_files = {}
|
| 24 |
|
| 25 |
@app.get("/", response_class=HTMLResponse)
|
| 26 |
async def home(request: Request):
|
|
|
|
| 29 |
@app.post("/create-room")
|
| 30 |
async def create_room():
|
| 31 |
"""Create a new chat room and return its ID"""
|
| 32 |
+
room_id = str(uuid.uuid4())[:8]
|
| 33 |
active_rooms[room_id] = []
|
| 34 |
+
room_files[room_id] = []
|
| 35 |
return {"room_id": room_id, "success": True}
|
| 36 |
|
| 37 |
+
@app.post("/upload-file/{room_id}")
|
| 38 |
+
async def upload_file(room_id: str, file: UploadFile = File(...)):
|
| 39 |
+
"""Handle file uploads for a room"""
|
| 40 |
+
if room_id not in active_rooms:
|
| 41 |
+
raise HTTPException(status_code=404, detail="Room not found")
|
| 42 |
+
|
| 43 |
+
# Generate unique filename
|
| 44 |
+
file_ext = Path(file.filename).suffix
|
| 45 |
+
unique_name = f"{uuid.uuid4().hex}{file_ext}"
|
| 46 |
+
file_path = UPLOAD_DIR / unique_name
|
| 47 |
+
|
| 48 |
+
# Save file
|
| 49 |
+
content = await file.read()
|
| 50 |
+
with open(file_path, "wb") as f:
|
| 51 |
+
f.write(content)
|
| 52 |
+
|
| 53 |
+
# Store file info
|
| 54 |
+
file_info = {
|
| 55 |
+
"filename": unique_name,
|
| 56 |
+
"original_name": file.filename,
|
| 57 |
+
"file_type": file.content_type or "application/octet-stream",
|
| 58 |
+
"size": len(content)
|
| 59 |
+
}
|
| 60 |
+
room_files[room_id].append(file_info)
|
| 61 |
+
|
| 62 |
+
return {
|
| 63 |
+
"success": True,
|
| 64 |
+
"file_url": f"/uploads/{unique_name}",
|
| 65 |
+
"file_info": file_info
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
@app.websocket("/ws/{room_id}")
|
| 69 |
async def websocket_endpoint(websocket: WebSocket, room_id: str):
|
| 70 |
"""Handle WebSocket connections for a specific room"""
|
|
|
|
| 91 |
|
| 92 |
try:
|
| 93 |
while True:
|
|
|
|
| 94 |
data = await websocket.receive_text()
|
| 95 |
message_data = json.loads(data)
|
| 96 |
|
| 97 |
# Broadcast to all users in the room
|
| 98 |
broadcast_message = json.dumps({
|
| 99 |
+
"type": message_data.get("type", "message"),
|
| 100 |
"username": message_data.get("username", "Anonymous"),
|
| 101 |
+
"text": message_data.get("text", ""),
|
| 102 |
+
"file": message_data.get("file", None)
|
| 103 |
})
|
| 104 |
|
| 105 |
for connection in active_rooms[room_id]:
|
|
|
|
| 109 |
pass
|
| 110 |
|
| 111 |
except WebSocketDisconnect:
|
|
|
|
| 112 |
if websocket in active_rooms[room_id]:
|
| 113 |
active_rooms[room_id].remove(websocket)
|
| 114 |
|
|
|
|
| 115 |
if not active_rooms[room_id]:
|
| 116 |
del active_rooms[room_id]
|
| 117 |
+
# Clean up files for empty room
|
| 118 |
+
if room_id in room_files:
|
| 119 |
+
for file_info in room_files[room_id]:
|
| 120 |
+
try:
|
| 121 |
+
(UPLOAD_DIR / file_info["filename"]).unlink()
|
| 122 |
+
except:
|
| 123 |
+
pass
|
| 124 |
+
del room_files[room_id]
|
| 125 |
else:
|
|
|
|
| 126 |
user_count = len(active_rooms[room_id])
|
| 127 |
leave_message = json.dumps({
|
| 128 |
"type": "system",
|