Files
spoolman2/spoolman/ws.py
Donkie a6d527aaf0 Added/deleted-type websocket messages
Events are now sent for not only when an object changes but also when one is created or deleted.

For now it's not really possible to subscribe to these events however.

This breaks backwards-compatibility with the websocket messages.
2023-10-15 19:46:10 +02:00

51 lines
1.5 KiB
Python

"""Websocket functionality."""
import logging
from fastapi import WebSocket
from spoolman.api.v1.models import Event
logger = logging.getLogger(__name__)
class WebsocketManager:
"""Websocket manager."""
def __init__(self) -> None:
"""Initialize."""
self.connections: dict[str, set[WebSocket]] = {}
def connect(self, pool: tuple[str, ...], websocket: WebSocket) -> None:
"""Connect a websocket."""
pool_str = ",".join(pool)
if pool_str not in self.connections:
self.connections[pool_str] = set()
self.connections[pool_str].add(websocket)
logger.info(
"Client %s is now listening on pool %s",
websocket.client.host if websocket.client else "?",
pool_str,
)
def disconnect(self, pool: tuple[str, ...], websocket: WebSocket) -> None:
"""Disconnect a websocket."""
pool_str = ",".join(pool)
if pool_str in self.connections:
self.connections[pool_str].remove(websocket)
logger.info(
"Client %s has stopped listening on pool %s",
websocket.client.host if websocket.client else "?",
pool_str,
)
async def send(self, pool: tuple[str, ...], evt: Event) -> None:
"""Send a message to all websockets in a pool."""
pool_str = ",".join(pool)
if pool_str in self.connections:
for websocket in self.connections[pool_str]:
await websocket.send_text(evt.json())
websocket_manager = WebsocketManager()