generateur_v3/backend/api/routes/room/manager.py

61 lines
2.3 KiB
Python
Raw Normal View History

2023-02-22 12:43:39 +01:00
from typing import TYPE_CHECKING, Dict, List, Callable, Any
2023-02-23 17:11:57 +01:00
2022-10-10 01:34:38 +02:00
from starlette.websockets import WebSocketState
2023-02-23 17:11:57 +01:00
2022-09-26 10:04:02 +02:00
if TYPE_CHECKING:
from routes.room.consumer import RoomConsumer
2022-10-10 01:34:38 +02:00
2022-09-26 10:04:02 +02:00
class RoomManager:
def __init__(self):
self.active_connections: Dict[str, List["RoomConsumer"]] = {}
def add(self, group: str, member: "RoomConsumer"):
if group not in self.active_connections:
self.active_connections[group] = []
if member not in self.active_connections[group]:
self.active_connections[group].append(member)
2022-10-10 01:34:38 +02:00
async def _send(self, connection: "RoomConsumer", message, group: str):
2023-02-28 10:21:08 +01:00
2023-02-22 12:43:39 +01:00
if connection.ws.application_state == WebSocketState.DISCONNECTED or connection.ws.client_state == WebSocketState.DISCONNECTED:
2022-10-10 01:34:38 +02:00
self.remove(group, connection)
2023-02-23 17:11:57 +01:00
elif connection.ws.application_state == WebSocketState.CONNECTED and connection.ws.client_state == WebSocketState.CONNECTED:
try:
await connection.send(message)
except:
pass
2022-10-10 01:34:38 +02:00
2022-09-26 10:04:02 +02:00
def remove(self, group: str, member: "RoomConsumer"):
if group in self.active_connections:
if member in self.active_connections[group]:
self.active_connections[group].remove(member)
2023-02-23 17:11:57 +01:00
return True
2022-09-26 10:04:02 +02:00
2023-02-22 12:43:39 +01:00
async def broadcast(self, message: Any | Callable, group: str, conditions: list[Callable] = [], exclude: list["RoomConsumer"] = [], ):
2023-02-28 10:21:08 +01:00
2023-02-23 17:11:57 +01:00
2023-02-22 12:43:39 +01:00
2022-09-26 10:04:02 +02:00
if group in self.active_connections:
for connection in list(set(self.active_connections[group])):
2023-02-23 17:11:57 +01:00
if connection not in exclude and all(f(connection) for f in conditions):
2022-10-10 01:34:38 +02:00
await self._send(connection, message, group)
2022-09-26 10:04:02 +02:00
async def send_to(self, group, id_code, msg):
2023-02-28 10:21:08 +01:00
2022-09-26 10:04:02 +02:00
if group in self.active_connections:
members = [c for c in self.active_connections[group]
if c.member.id_code == id_code]
2023-02-28 10:21:08 +01:00
2022-09-26 10:04:02 +02:00
for m in members:
2022-10-10 01:34:38 +02:00
await self._send(m, msg, group)
2022-09-26 10:04:02 +02:00
async def send_to_admin(self, group, msg):
if group in self.active_connections:
2023-02-28 10:21:08 +01:00
2022-09-26 10:04:02 +02:00
members = [c for c in self.active_connections[group]
2023-02-23 17:11:57 +01:00
if c.member is not None and c.member.is_admin is True]
2022-09-26 10:04:02 +02:00
for m in members:
2022-10-10 01:34:38 +02:00
await self._send(m, msg, group)