collabrix/backend/app/websocket.py
DGSoft 93b98cfb5c Initial commit: Team Chat System with Code Snippet Library
- Complete chat application similar to Microsoft Teams
- Code snippet library with syntax highlighting
- Real-time messaging with WebSockets
- File upload with Office integration
- Department-based permissions
- Dark/Light theme support
- Production deployment with SSL/Reverse Proxy
- Docker containerization
- PostgreSQL database with SQLModel ORM
2025-12-09 22:25:03 +01:00

52 lines
2.0 KiB
Python

from fastapi import WebSocket, WebSocketDisconnect
from typing import Dict, List
import json
class ConnectionManager:
def __init__(self):
# Maps channel_id to list of WebSocket connections
self.active_connections: Dict[int, List[WebSocket]] = {}
async def connect(self, websocket: WebSocket, channel_id: int):
"""Accept a new WebSocket connection for a channel"""
await websocket.accept()
if channel_id not in self.active_connections:
self.active_connections[channel_id] = []
self.active_connections[channel_id].append(websocket)
def disconnect(self, websocket: WebSocket, channel_id: int):
"""Remove a WebSocket connection"""
if channel_id in self.active_connections:
if websocket in self.active_connections[channel_id]:
self.active_connections[channel_id].remove(websocket)
# Clean up empty channel lists
if not self.active_connections[channel_id]:
del self.active_connections[channel_id]
async def send_personal_message(self, message: str, websocket: WebSocket):
"""Send a message to a specific WebSocket"""
await websocket.send_text(message)
async def broadcast_to_channel(self, message: dict, channel_id: int):
"""Broadcast a message to all connections in a channel"""
if channel_id in self.active_connections:
message_str = json.dumps(message)
disconnected = []
for connection in self.active_connections[channel_id]:
try:
await connection.send_text(message_str)
except Exception:
# Mark for removal if send fails
disconnected.append(connection)
# Remove disconnected clients
for connection in disconnected:
self.disconnect(connection, channel_id)
# Global connection manager instance
manager = ConnectionManager()