Update main.py
Browse files
main.py
CHANGED
|
@@ -10,29 +10,22 @@ from fastapi.middleware.cors import CORSMiddleware
|
|
| 10 |
|
| 11 |
app = FastAPI(title="Antaram Chat")
|
| 12 |
|
| 13 |
-
# --- Fix: Add CORS to allow connections from localhost/cloud ---
|
| 14 |
app.add_middleware(
|
| 15 |
CORSMiddleware,
|
| 16 |
-
allow_origins=["*"],
|
| 17 |
allow_credentials=True,
|
| 18 |
allow_methods=["*"],
|
| 19 |
allow_headers=["*"],
|
| 20 |
)
|
| 21 |
|
| 22 |
-
# Setup Directories
|
| 23 |
BASE_DIR = Path(__file__).resolve().parent
|
| 24 |
UPLOAD_DIR = BASE_DIR / "uploads"
|
| 25 |
UPLOAD_DIR.mkdir(exist_ok=True)
|
| 26 |
|
| 27 |
-
# Templates
|
| 28 |
templates = Jinja2Templates(directory="templates")
|
| 29 |
-
|
| 30 |
-
# Mount static files (for uploaded images)
|
| 31 |
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
|
| 32 |
|
| 33 |
-
# Store active rooms: {room_id: [websocket_connections]}
|
| 34 |
active_rooms = {}
|
| 35 |
-
# Store uploaded files info: {room_id: [{filename, original_name, file_type}]}
|
| 36 |
room_files = {}
|
| 37 |
|
| 38 |
@app.get("/", response_class=HTMLResponse)
|
|
@@ -41,119 +34,90 @@ async def home(request: Request):
|
|
| 41 |
|
| 42 |
@app.post("/create-room")
|
| 43 |
async def create_room():
|
| 44 |
-
|
| 45 |
-
room_id = str(uuid.uuid4())[:8].upper() # Using uppercase for easier reading
|
| 46 |
active_rooms[room_id] = []
|
| 47 |
room_files[room_id] = []
|
| 48 |
-
print(f"Room Created: {room_id}") # Debug log
|
| 49 |
return {"room_id": room_id, "success": True}
|
| 50 |
|
| 51 |
@app.post("/upload-file/{room_id}")
|
| 52 |
async def upload_file(room_id: str, file: UploadFile = File(...)):
|
| 53 |
-
"""Handle file uploads for a room"""
|
| 54 |
-
# Check if room exists in active_rooms OR room_files (in case WS hasn't connected yet)
|
| 55 |
if room_id not in room_files:
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
-
# Generate unique filename
|
| 59 |
file_ext = Path(file.filename).suffix
|
| 60 |
unique_name = f"{uuid.uuid4().hex}{file_ext}"
|
| 61 |
file_path = UPLOAD_DIR / unique_name
|
| 62 |
|
| 63 |
-
# Save file
|
| 64 |
content = await file.read()
|
| 65 |
with open(file_path, "wb") as f:
|
| 66 |
f.write(content)
|
| 67 |
|
| 68 |
-
# Store file info
|
| 69 |
file_info = {
|
| 70 |
"filename": unique_name,
|
| 71 |
"original_name": file.filename,
|
| 72 |
"file_type": file.content_type or "application/octet-stream",
|
| 73 |
"size": len(content),
|
| 74 |
-
"file_url": f"/uploads/{unique_name}"
|
| 75 |
}
|
| 76 |
room_files[room_id].append(file_info)
|
| 77 |
|
| 78 |
-
return {
|
| 79 |
-
"success": True,
|
| 80 |
-
"file_info": file_info
|
| 81 |
-
}
|
| 82 |
|
| 83 |
@app.websocket("/ws/{room_id}")
|
| 84 |
async def websocket_endpoint(websocket: WebSocket, room_id: str):
|
| 85 |
-
"""Handle WebSocket connections for a specific room"""
|
| 86 |
-
|
| 87 |
-
# 1. Validate Room Existence
|
| 88 |
if room_id not in active_rooms:
|
| 89 |
-
|
| 90 |
-
# 1000 = Normal Closure, but usually we imply an error.
|
| 91 |
-
# Note: Sending text before accept is risky, so we just close.
|
| 92 |
-
await websocket.close(code=1008) # 1008 = Policy Violation (Room doesn't exist)
|
| 93 |
return
|
| 94 |
|
| 95 |
-
# 2. Accept Connection
|
| 96 |
await websocket.accept()
|
| 97 |
active_rooms[room_id].append(websocket)
|
| 98 |
|
| 99 |
-
#
|
| 100 |
user_count = len(active_rooms[room_id])
|
| 101 |
-
|
| 102 |
"type": "system",
|
| 103 |
-
"message": "A user
|
| 104 |
"userCount": user_count
|
| 105 |
-
})
|
| 106 |
-
|
| 107 |
-
await broadcast_to_room(room_id, system_message)
|
| 108 |
|
| 109 |
try:
|
| 110 |
while True:
|
| 111 |
-
# 4. Listen for messages
|
| 112 |
data = await websocket.receive_text()
|
| 113 |
message_data = json.loads(data)
|
| 114 |
|
| 115 |
-
|
| 116 |
-
broadcast_payload = json.dumps({
|
| 117 |
"type": message_data.get("type", "message"),
|
| 118 |
"username": message_data.get("username", "Anonymous"),
|
| 119 |
"text": message_data.get("text", ""),
|
| 120 |
"file": message_data.get("file", None)
|
| 121 |
})
|
| 122 |
-
|
| 123 |
-
# 5. Broadcast to ALL users (including sender, for sync)
|
| 124 |
-
await broadcast_to_room(room_id, broadcast_payload)
|
| 125 |
|
| 126 |
except WebSocketDisconnect:
|
| 127 |
if room_id in active_rooms and websocket in active_rooms[room_id]:
|
| 128 |
active_rooms[room_id].remove(websocket)
|
| 129 |
-
|
| 130 |
if not active_rooms[room_id]:
|
| 131 |
-
# If room is empty, clean up
|
| 132 |
del active_rooms[room_id]
|
| 133 |
-
if room_id in room_files:
|
| 134 |
-
# Optional: Delete actual files here if you want temporary storage
|
| 135 |
-
del room_files[room_id]
|
| 136 |
-
print(f"Room {room_id} deleted (empty)")
|
| 137 |
else:
|
| 138 |
-
# Notify remaining users
|
| 139 |
user_count = len(active_rooms[room_id])
|
| 140 |
-
|
| 141 |
"type": "system",
|
| 142 |
-
"message": "A user
|
| 143 |
"userCount": user_count
|
| 144 |
-
})
|
| 145 |
-
await broadcast_to_room(room_id, leave_message)
|
| 146 |
|
| 147 |
async def broadcast_to_room(room_id: str, message: str):
|
| 148 |
-
"""Helper to send message to all sockets in a room"""
|
| 149 |
if room_id in active_rooms:
|
| 150 |
for connection in active_rooms[room_id]:
|
| 151 |
try:
|
| 152 |
await connection.send_text(message)
|
| 153 |
-
except
|
| 154 |
-
print(f"Error broadcasting: {e}")
|
| 155 |
|
| 156 |
if __name__ == "__main__":
|
| 157 |
import uvicorn
|
| 158 |
-
# Run with: python main.py
|
| 159 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 10 |
|
| 11 |
app = FastAPI(title="Antaram Chat")
|
| 12 |
|
|
|
|
| 13 |
app.add_middleware(
|
| 14 |
CORSMiddleware,
|
| 15 |
+
allow_origins=["*"],
|
| 16 |
allow_credentials=True,
|
| 17 |
allow_methods=["*"],
|
| 18 |
allow_headers=["*"],
|
| 19 |
)
|
| 20 |
|
|
|
|
| 21 |
BASE_DIR = Path(__file__).resolve().parent
|
| 22 |
UPLOAD_DIR = BASE_DIR / "uploads"
|
| 23 |
UPLOAD_DIR.mkdir(exist_ok=True)
|
| 24 |
|
|
|
|
| 25 |
templates = Jinja2Templates(directory="templates")
|
|
|
|
|
|
|
| 26 |
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
|
| 27 |
|
|
|
|
| 28 |
active_rooms = {}
|
|
|
|
| 29 |
room_files = {}
|
| 30 |
|
| 31 |
@app.get("/", response_class=HTMLResponse)
|
|
|
|
| 34 |
|
| 35 |
@app.post("/create-room")
|
| 36 |
async def create_room():
|
| 37 |
+
room_id = str(uuid.uuid4())[:8].upper()
|
|
|
|
| 38 |
active_rooms[room_id] = []
|
| 39 |
room_files[room_id] = []
|
|
|
|
| 40 |
return {"room_id": room_id, "success": True}
|
| 41 |
|
| 42 |
@app.post("/upload-file/{room_id}")
|
| 43 |
async def upload_file(room_id: str, file: UploadFile = File(...)):
|
|
|
|
|
|
|
| 44 |
if room_id not in room_files:
|
| 45 |
+
# If the room exists in active_rooms but no files yet, initialize list
|
| 46 |
+
if room_id in active_rooms:
|
| 47 |
+
room_files[room_id] = []
|
| 48 |
+
else:
|
| 49 |
+
raise HTTPException(status_code=404, detail="Room not found")
|
| 50 |
|
|
|
|
| 51 |
file_ext = Path(file.filename).suffix
|
| 52 |
unique_name = f"{uuid.uuid4().hex}{file_ext}"
|
| 53 |
file_path = UPLOAD_DIR / unique_name
|
| 54 |
|
|
|
|
| 55 |
content = await file.read()
|
| 56 |
with open(file_path, "wb") as f:
|
| 57 |
f.write(content)
|
| 58 |
|
|
|
|
| 59 |
file_info = {
|
| 60 |
"filename": unique_name,
|
| 61 |
"original_name": file.filename,
|
| 62 |
"file_type": file.content_type or "application/octet-stream",
|
| 63 |
"size": len(content),
|
| 64 |
+
"file_url": f"/uploads/{unique_name}"
|
| 65 |
}
|
| 66 |
room_files[room_id].append(file_info)
|
| 67 |
|
| 68 |
+
return {"success": True, "file_info": file_info}
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
@app.websocket("/ws/{room_id}")
|
| 71 |
async def websocket_endpoint(websocket: WebSocket, room_id: str):
|
|
|
|
|
|
|
|
|
|
| 72 |
if room_id not in active_rooms:
|
| 73 |
+
await websocket.close(code=1008)
|
|
|
|
|
|
|
|
|
|
| 74 |
return
|
| 75 |
|
|
|
|
| 76 |
await websocket.accept()
|
| 77 |
active_rooms[room_id].append(websocket)
|
| 78 |
|
| 79 |
+
# Notify Join
|
| 80 |
user_count = len(active_rooms[room_id])
|
| 81 |
+
await broadcast_to_room(room_id, json.dumps({
|
| 82 |
"type": "system",
|
| 83 |
+
"message": "A user joined.",
|
| 84 |
"userCount": user_count
|
| 85 |
+
}))
|
|
|
|
|
|
|
| 86 |
|
| 87 |
try:
|
| 88 |
while True:
|
|
|
|
| 89 |
data = await websocket.receive_text()
|
| 90 |
message_data = json.loads(data)
|
| 91 |
|
| 92 |
+
payload = json.dumps({
|
|
|
|
| 93 |
"type": message_data.get("type", "message"),
|
| 94 |
"username": message_data.get("username", "Anonymous"),
|
| 95 |
"text": message_data.get("text", ""),
|
| 96 |
"file": message_data.get("file", None)
|
| 97 |
})
|
| 98 |
+
await broadcast_to_room(room_id, payload)
|
|
|
|
|
|
|
| 99 |
|
| 100 |
except WebSocketDisconnect:
|
| 101 |
if room_id in active_rooms and websocket in active_rooms[room_id]:
|
| 102 |
active_rooms[room_id].remove(websocket)
|
|
|
|
| 103 |
if not active_rooms[room_id]:
|
|
|
|
| 104 |
del active_rooms[room_id]
|
| 105 |
+
if room_id in room_files: del room_files[room_id]
|
|
|
|
|
|
|
|
|
|
| 106 |
else:
|
|
|
|
| 107 |
user_count = len(active_rooms[room_id])
|
| 108 |
+
await broadcast_to_room(room_id, json.dumps({
|
| 109 |
"type": "system",
|
| 110 |
+
"message": "A user left.",
|
| 111 |
"userCount": user_count
|
| 112 |
+
}))
|
|
|
|
| 113 |
|
| 114 |
async def broadcast_to_room(room_id: str, message: str):
|
|
|
|
| 115 |
if room_id in active_rooms:
|
| 116 |
for connection in active_rooms[room_id]:
|
| 117 |
try:
|
| 118 |
await connection.send_text(message)
|
| 119 |
+
except: pass
|
|
|
|
| 120 |
|
| 121 |
if __name__ == "__main__":
|
| 122 |
import uvicorn
|
|
|
|
| 123 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|