2021-02-26 15:39:35 +00:00
|
|
|
import json
|
2021-04-03 17:36:01 +00:00
|
|
|
import logging
|
2021-02-26 15:39:35 +00:00
|
|
|
|
|
|
|
from app.classes.shared.console import console
|
|
|
|
|
2021-04-03 17:36:01 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2021-02-26 15:39:35 +00:00
|
|
|
class WebSocketHelper:
|
|
|
|
clients = set()
|
|
|
|
|
|
|
|
def addClient(self, client):
|
|
|
|
self.clients.add(client)
|
|
|
|
|
|
|
|
def removeClient(self, client):
|
|
|
|
self.clients.add(client)
|
2021-03-01 00:54:20 +00:00
|
|
|
|
|
|
|
def send_message(self, client, event_type, data):
|
2021-03-01 17:33:15 +00:00
|
|
|
if client.check_auth():
|
|
|
|
message = str(json.dumps({'event': event_type, 'data': data}))
|
|
|
|
client.write_message(message)
|
2021-02-26 15:39:35 +00:00
|
|
|
|
2021-03-01 00:54:20 +00:00
|
|
|
def broadcast(self, event_type, data):
|
2021-04-03 17:36:01 +00:00
|
|
|
logger.debug('Sending: ' + str(json.dumps({'event': event_type, 'data': data})))
|
2021-02-26 15:39:35 +00:00
|
|
|
for client in self.clients:
|
|
|
|
try:
|
2021-03-01 00:54:20 +00:00
|
|
|
self.send_message(client, event_type, data)
|
2021-02-26 15:39:35 +00:00
|
|
|
except:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def disconnect_all(self):
|
|
|
|
console.info('Disconnecting WebSocket clients')
|
|
|
|
for client in self.clients:
|
|
|
|
client.close()
|
|
|
|
console.info('Disconnected WebSocket clients')
|
|
|
|
|
|
|
|
websocket_helper = WebSocketHelper()
|