1
0
mirror of https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git synced 2025-08-14 00:25:46 +02:00

add websockets support22

This commit is contained in:
MoonTestUse1
2025-01-05 01:45:09 +06:00
parent 2000ed7c13
commit df9af0131c
3 changed files with 66 additions and 29 deletions

View File

@@ -1,6 +1,9 @@
from fastapi import WebSocket
from typing import Dict, List
import json
import logging
logger = logging.getLogger(__name__)
class NotificationManager:
def __init__(self):
@@ -12,25 +15,47 @@ class NotificationManager:
async def connect(self, websocket: WebSocket, client_type: str):
await websocket.accept()
self.active_connections[client_type].append(websocket)
logger.info(f"New {client_type} connection. Total connections: {len(self.active_connections[client_type])}")
def disconnect(self, websocket: WebSocket, client_type: str):
self.active_connections[client_type].remove(websocket)
if websocket in self.active_connections[client_type]:
self.active_connections[client_type].remove(websocket)
logger.info(f"{client_type} disconnected. Remaining connections: {len(self.active_connections[client_type])}")
async def broadcast_to_admins(self, message: dict):
"""Отправка сообщения всем подключенным админам"""
logger.info(f"Broadcasting to admins: {message}")
disconnected = []
for connection in self.active_connections["admin"]:
try:
await connection.send_json(message)
except:
# Если не удалось отправить сообщение, пропускаем
logger.info("Message sent successfully")
except Exception as e:
logger.error(f"Error sending message: {e}")
disconnected.append(connection)
continue
# Удаляем отключенные соединения
for connection in disconnected:
self.disconnect(connection, "admin")
async def broadcast_to_employees(self, employee_id: int, message: dict):
"""Отправка сообщения конкретному сотруднику"""
logger.info(f"Broadcasting to employee {employee_id}: {message}")
disconnected = []
for connection in self.active_connections["employee"]:
try:
await connection.send_json(message)
except:
logger.info("Message sent successfully")
except Exception as e:
logger.error(f"Error sending message: {e}")
disconnected.append(connection)
continue
# Удаляем отключенные соединения
for connection in disconnected:
self.disconnect(connection, "employee")
notification_manager = NotificationManager()