2021-02-26 17:39:35 +02:00
|
|
|
import json
|
|
|
|
|
|
|
|
from app.classes.shared.console import console
|
|
|
|
|
|
|
|
class WebSocketHelper:
|
|
|
|
clients = set()
|
|
|
|
|
|
|
|
def addClient(self, client):
|
|
|
|
self.clients.add(client)
|
|
|
|
|
|
|
|
def removeClient(self, client):
|
|
|
|
self.clients.add(client)
|
2021-03-01 02:54:20 +02:00
|
|
|
|
|
|
|
def send_message(self, client, event_type, data):
|
2021-03-01 19:33:15 +02:00
|
|
|
if client.check_auth():
|
|
|
|
message = str(json.dumps({'event': event_type, 'data': data}))
|
|
|
|
client.write_message(message)
|
2021-02-26 17:39:35 +02:00
|
|
|
|
2021-03-01 02:54:20 +02:00
|
|
|
def broadcast(self, event_type, data):
|
|
|
|
console.debug('Sending: ' + str(json.dumps({'event': event_type, 'data': data})))
|
2021-02-26 17:39:35 +02:00
|
|
|
for client in self.clients:
|
|
|
|
try:
|
2021-03-01 02:54:20 +02:00
|
|
|
self.send_message(client, event_type, data)
|
2021-02-26 17:39:35 +02: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()
|