Reverting Public/Auth websocket

This commit is contained in:
Silversthorn 2023-09-05 23:00:52 +02:00
parent c7ea7fbc6b
commit a0b069c9ef
4 changed files with 48 additions and 66 deletions

View File

@ -93,7 +93,7 @@ class ServerOutBuf:
# TODO: Do not send data to clients who do not have permission to view # TODO: Do not send data to clients who do not have permission to view
# this server's console # this server's console
if len(WebSocketManager().auth_clients) > 0: if len(WebSocketManager().clients) > 0:
WebSocketManager().broadcast_page_params( WebSocketManager().broadcast_page_params(
"/panel/server_detail", "/panel/server_detail",
{"id": self.server_id}, {"id": self.server_id},
@ -1047,7 +1047,7 @@ class ServerInstance:
logger.info(f"Backup Thread started for server {self.settings['server_name']}.") logger.info(f"Backup Thread started for server {self.settings['server_name']}.")
def a_backup_server(self): def a_backup_server(self):
if len(WebSocketManager().auth_clients) > 0: if len(WebSocketManager().clients) > 0:
WebSocketManager().broadcast_page_params( WebSocketManager().broadcast_page_params(
"/panel/server_detail", "/panel/server_detail",
{"id": str(self.server_id)}, {"id": str(self.server_id)},
@ -1133,7 +1133,7 @@ class ServerInstance:
self.is_backingup = False self.is_backingup = False
logger.info(f"Backup of server: {self.name} completed") logger.info(f"Backup of server: {self.name} completed")
results = {"percent": 100, "total_files": 0, "current_file": 0} results = {"percent": 100, "total_files": 0, "current_file": 0}
if len(WebSocketManager().auth_clients) > 0: if len(WebSocketManager().clients) > 0:
WebSocketManager().broadcast_page_params( WebSocketManager().broadcast_page_params(
"/panel/server_detail", "/panel/server_detail",
{"id": str(self.server_id)}, {"id": str(self.server_id)},
@ -1189,7 +1189,7 @@ class ServerInstance:
def backup_status(self, source_path, dest_path): def backup_status(self, source_path, dest_path):
results = Helpers.calc_percent(source_path, dest_path) results = Helpers.calc_percent(source_path, dest_path)
self.backup_stats = results self.backup_stats = results
if len(WebSocketManager().auth_clients) > 0: if len(WebSocketManager().clients) > 0:
WebSocketManager().broadcast_page_params( WebSocketManager().broadcast_page_params(
"/panel/server_detail", "/panel/server_detail",
{"id": str(self.server_id)}, {"id": str(self.server_id)},
@ -1293,7 +1293,7 @@ class ServerInstance:
self.stop_threaded_server() self.stop_threaded_server()
else: else:
was_started = False was_started = False
if len(WebSocketManager().auth_clients) > 0: if len(WebSocketManager().clients) > 0:
# There are clients # There are clients
self.check_update() self.check_update()
message = ( message = (
@ -1399,7 +1399,7 @@ class ServerInstance:
logger.info("Executable updated successfully. Starting Server") logger.info("Executable updated successfully. Starting Server")
self.stats_helper.set_update(False) self.stats_helper.set_update(False)
if len(WebSocketManager().auth_clients) > 0: if len(WebSocketManager().clients) > 0:
# There are clients # There are clients
self.check_update() self.check_update()
for user in server_users: for user in server_users:
@ -1480,7 +1480,7 @@ class ServerInstance:
def realtime_stats(self): def realtime_stats(self):
# only get stats if clients are connected. # only get stats if clients are connected.
# no point in burning cpu # no point in burning cpu
if len(WebSocketManager().public_clients | WebSocketManager().auth_clients) > 0: if len(WebSocketManager().clients) > 0:
total_players = 0 total_players = 0
max_players = 0 max_players = 0
servers_ping = [] servers_ping = []
@ -1511,7 +1511,7 @@ class ServerInstance:
"crashed": self.is_crashed, "crashed": self.is_crashed,
} }
) )
if len(WebSocketManager().auth_clients) > 0:
WebSocketManager().broadcast_page_params( WebSocketManager().broadcast_page_params(
"/panel/server_detail", "/panel/server_detail",
{"id": str(self.server_id)}, {"id": str(self.server_id)},
@ -1534,9 +1534,7 @@ class ServerInstance:
"version": raw_ping_result.get("version"), "version": raw_ping_result.get("version"),
"icon": raw_ping_result.get("icon"), "icon": raw_ping_result.get("icon"),
"crashed": self.is_crashed, "crashed": self.is_crashed,
"created": datetime.datetime.now().strftime( "created": datetime.datetime.now().strftime("%Y/%m/%d, %H:%M:%S"),
"%Y/%m/%d, %H:%M:%S"
),
"players_cache": self.player_cache, "players_cache": self.player_cache,
}, },
) )
@ -1545,7 +1543,7 @@ class ServerInstance:
# self.record_server_stats() # self.record_server_stats()
if (len(servers_ping) > 0) & (len(WebSocketManager().auth_clients) > 0): if len(servers_ping) > 0:
try: try:
WebSocketManager().broadcast_page( WebSocketManager().broadcast_page(
"/panel/dashboard", "update_server_status", servers_ping "/panel/dashboard", "update_server_status", servers_ping

View File

@ -689,7 +689,7 @@ class TasksManager:
# Stats are different # Stats are different
host_stats = HelpersManagement.get_latest_hosts_stats() host_stats = HelpersManagement.get_latest_hosts_stats()
if len(WebSocketManager().auth_clients) > 0: if len(WebSocketManager().clients) > 0:
# There are clients # There are clients
try: try:
WebSocketManager().broadcast_page( WebSocketManager().broadcast_page(

View File

@ -1,6 +1,5 @@
import json import json
import logging import logging
from enum import Enum
from app.classes.shared.singleton import Singleton from app.classes.shared.singleton import Singleton
from app.classes.shared.console import Console from app.classes.shared.console import Console
@ -9,38 +8,25 @@ from app.classes.models.users import HelperUsers
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class EnumWebSocketState(Enum):
WS_UNKNOWN = -1
WS_PUBLIC = 0
WS_USER_AUTH = 1
class WebSocketManager(metaclass=Singleton): class WebSocketManager(metaclass=Singleton):
def __init__(self): def __init__(self):
self.auth_clients = set() self.clients = set()
self.public_clients = set()
def add_client(self, client): def add_client(self, client):
if client.ws_state == EnumWebSocketState.WS_PUBLIC: self.clients.add(client)
self.public_clients.add(client)
elif client.ws_state == EnumWebSocketState.WS_USER_AUTH:
self.auth_clients.add(client)
else:
logging.debug("Unknown WebSocket")
client.close()
def remove_client(self, client): def remove_client(self, client):
if client.ws_state == EnumWebSocketState.WS_PUBLIC: if client in self.clients:
self.public_clients.remove(client) self.clients.remove(client)
elif client.ws_state == EnumWebSocketState.WS_USER_AUTH: else:
self.auth_clients.remove(client) logger.exception("Error caught while removing unknown WebSocket client")
def broadcast(self, event_type: str, data): def broadcast(self, event_type: str, data):
logger.debug( logger.debug(
f"Sending to {len(self.public_clients | self.auth_clients)} clients: " f"Sending to {len(self.clients)} clients: "
f"{json.dumps({'event': event_type, 'data': data})}" f"{json.dumps({'event': event_type, 'data': data})}"
) )
for client in self.public_clients | self.auth_clients: for client in self.clients:
try: try:
client.send_message(event_type, data) client.send_message(event_type, data)
except Exception as e: except Exception as e:
@ -108,11 +94,11 @@ class WebSocketManager(metaclass=Singleton):
def broadcast_with_fn(self, filter_fn, event_type: str, data): def broadcast_with_fn(self, filter_fn, event_type: str, data):
# assign self.clients to a static variable here so hopefully # assign self.clients to a static variable here so hopefully
# the set size won't change # the set size won't change
static_clients = self.public_clients | self.auth_clients static_clients = self.clients
clients = list(filter(filter_fn, static_clients)) clients = list(filter(filter_fn, static_clients))
logger.debug( logger.debug(
f"Sending to {len(clients)} \ f"Sending to {len(clients)} \
out of {len(self.public_clients | self.auth_clients)} " out of {len(self.clients)} "
f"clients: {json.dumps({'event': event_type, 'data': data})}" f"clients: {json.dumps({'event': event_type, 'data': data})}"
) )
@ -127,6 +113,6 @@ class WebSocketManager(metaclass=Singleton):
def disconnect_all(self): def disconnect_all(self):
Console.info("Disconnecting WebSocket clients") Console.info("Disconnecting WebSocket clients")
for client in self.public_clients | self.auth_clients: for client in self.clients:
client.close() client.close()
Console.info("Disconnected WebSocket clients") Console.info("Disconnected WebSocket clients")

View File

@ -6,13 +6,12 @@ import tornado.websocket
from app.classes.shared.main_controller import Controller from app.classes.shared.main_controller import Controller
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
from app.classes.shared.websocket_manager import WebSocketManager, EnumWebSocketState from app.classes.shared.websocket_manager import WebSocketManager
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class BaseSocketHandler(tornado.websocket.WebSocketHandler): class BaseSocketHandler(tornado.websocket.WebSocketHandler):
ws_state = EnumWebSocketState.WS_UNKNOWN # Must be overridden at init
ws_authorized_pages = {} # Must be overridden at init ws_authorized_pages = {} # Must be overridden at init
ws_authorized_events = {} # Must be overridden at init ws_authorized_events = {} # Must be overridden at init
page = None page = None
@ -104,7 +103,6 @@ class BaseSocketHandler(tornado.websocket.WebSocketHandler):
class SocketHandler(BaseSocketHandler): class SocketHandler(BaseSocketHandler):
ws_state = EnumWebSocketState.WS_USER_AUTH
ws_authorized_pages = {"panel", "server", "ajax", "files", "upload", "api"} ws_authorized_pages = {"panel", "server", "ajax", "files", "upload", "api"}
ws_authorized_events = { ws_authorized_events = {
"notification", "notification",