channel.py 1005 B

12345678910111213141516171819202122232425262728293031323334353637
  1. from typing import Dict
  2. from websockets import WebSocketServerProtocol
  3. class Subscriber:
  4. player_enabled = False
  5. ws: WebSocketServerProtocol
  6. def __init__(self, ws):
  7. self.ws = ws
  8. class Channel:
  9. subscribers: Dict[WebSocketServerProtocol, Subscriber]
  10. def __init__(self):
  11. self.subscribers = dict()
  12. def subscribe(self, ws: WebSocketServerProtocol):
  13. if ws not in self.subscribers:
  14. self.subscribers[ws] = (Subscriber(ws))
  15. def unsubscribe(self, ws: WebSocketServerProtocol):
  16. if ws in self.subscribers:
  17. self.subscribers.pop(ws)
  18. def get_player_enabled_subscribers(self):
  19. return filter(lambda s: s.player_enabled, self.subscribers.values())
  20. async def send(self, message):
  21. for sub in list(self.subscribers.values()):
  22. if sub.ws.open:
  23. await sub.ws.send(message)
  24. else:
  25. print("closed ws still in channel")
  26. self.unsubscribe(sub.ws)