channel.py 979 B

123456789101112131415161718192021222324252627282930313233343536
  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. await sub.ws.send(message)
  23. # else:
  24. # print("closed ws still in channel")
  25. # self.unsubscribe(sub.ws)