2022-09-26 10:04:02 +02:00
|
|
|
from typing import TYPE_CHECKING, Dict, List
|
2022-10-10 01:34:38 +02:00
|
|
|
from starlette.websockets import WebSocketState
|
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):
|
|
|
|
if connection.ws.application_state == WebSocketState.DISCONNECTED:
|
|
|
|
self.remove(group, connection)
|
|
|
|
elif connection.ws.application_state == WebSocketState.CONNECTED:
|
|
|
|
await connection.send(message)
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
async def broadcast(self, message, group: str, exclude: list["RoomConsumer"] = []):
|
2022-10-10 01:34:38 +02:00
|
|
|
print('BROADCaST', message)
|
2022-09-26 10:04:02 +02:00
|
|
|
if group in self.active_connections:
|
|
|
|
for connection in list(set(self.active_connections[group])):
|
2022-10-10 01:34:38 +02:00
|
|
|
# print(connection)
|
2022-09-26 10:04:02 +02:00
|
|
|
if connection not in exclude:
|
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):
|
|
|
|
if group in self.active_connections:
|
|
|
|
members = [c for c in self.active_connections[group]
|
|
|
|
if c.member.id_code == id_code]
|
|
|
|
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:
|
|
|
|
members = [c for c in self.active_connections[group]
|
|
|
|
if c.member.is_admin == True]
|
|
|
|
for m in members:
|
2022-10-10 01:34:38 +02:00
|
|
|
await self._send(m, msg, group)
|