From 34fe9c13267c0757bdb7c4447f79821810da5f76 Mon Sep 17 00:00:00 2001 From: Silversthorn Date: Sat, 2 Sep 2023 21:51:28 +0200 Subject: [PATCH] Using API Call for Status Page --- app/classes/models/server_stats.py | 2 + app/classes/shared/server.py | 11 +- app/classes/web/routes/api/api_handlers.py | 9 ++ .../web/routes/api/servers/server/status.py | 32 +++++ app/classes/web/tornado_handler.py | 3 +- app/classes/web/websocket_handler.py | 42 ------ app/frontend/templates/panel/dashboard.html | 130 ++++++------------ app/frontend/templates/public/status.html | 47 +++++-- app/frontend/templates/public_base.html | 113 --------------- app/migrations/stats/20230827_add_icon.py | 16 +++ 10 files changed, 137 insertions(+), 268 deletions(-) create mode 100644 app/classes/web/routes/api/servers/server/status.py create mode 100644 app/migrations/stats/20230827_add_icon.py diff --git a/app/classes/models/server_stats.py b/app/classes/models/server_stats.py index d3b8cdf0..5a38ac1e 100644 --- a/app/classes/models/server_stats.py +++ b/app/classes/models/server_stats.py @@ -50,6 +50,7 @@ class ServerStats(Model): max = IntegerField(default=0) players = CharField(default="") desc = CharField(default="Unable to Connect") + icon = CharField(default="") version = CharField(default="") updating = BooleanField(default=False) waiting_start = BooleanField(default=False) @@ -183,6 +184,7 @@ class HelperServerStats: ServerStats.max: server_stats.get("max", False), ServerStats.players: server_stats.get("players", False), ServerStats.desc: server_stats.get("desc", False), + ServerStats.icon: server_stats.get("icon", None), ServerStats.version: server_stats.get("version", False), } ).execute(self.database) diff --git a/app/classes/shared/server.py b/app/classes/shared/server.py index 4682c22a..45675de5 100644 --- a/app/classes/shared/server.py +++ b/app/classes/shared/server.py @@ -1536,14 +1536,6 @@ class ServerInstance: except: Console.critical("Can't broadcast server status to websocket") - if (len(servers_ping) > 0) & (len(WebSocketManager().public_clients) > 0): - try: - WebSocketManager().broadcast_page( - "/status", "update_server_status", servers_ping - ) - except: - Console.critical("Can't broadcast server status to websocket") - def get_servers_stats(self): server_stats = {} @@ -1605,6 +1597,7 @@ class ServerInstance: "players": ping_data.get("players", False), "desc": ping_data.get("server_description", False), "version": ping_data.get("server_version", False), + "icon": ping_data.get("server_icon"), } else: server_stats = { @@ -1623,6 +1616,7 @@ class ServerInstance: "players": False, "desc": False, "version": False, + "icon": None, } return server_stats @@ -1671,7 +1665,6 @@ class ServerInstance: } server_stats = {} - server = HelperServers.get_server_obj(server_id) if not server: return {} server_dt = HelperServers.get_server_data_by_id(server_id) diff --git a/app/classes/web/routes/api/api_handlers.py b/app/classes/web/routes/api/api_handlers.py index 36eeb4f0..30e4d0d0 100644 --- a/app/classes/web/routes/api/api_handlers.py +++ b/app/classes/web/routes/api/api_handlers.py @@ -12,6 +12,7 @@ from app.classes.web.routes.api.roles.index import ApiRolesIndexHandler from app.classes.web.routes.api.roles.role.index import ApiRolesRoleIndexHandler from app.classes.web.routes.api.roles.role.servers import ApiRolesRoleServersHandler from app.classes.web.routes.api.roles.role.users import ApiRolesRoleUsersHandler + from app.classes.web.routes.api.servers.index import ApiServersIndexHandler from app.classes.web.routes.api.servers.server.action import ( ApiServersServerActionHandler, @@ -21,6 +22,9 @@ from app.classes.web.routes.api.servers.server.logs import ApiServersServerLogsH from app.classes.web.routes.api.servers.server.public import ( ApiServersServerPublicHandler, ) +from app.classes.web.routes.api.servers.server.status import ( + ApiServersServerStatusHandler, +) from app.classes.web.routes.api.servers.server.stats import ApiServersServerStatsHandler from app.classes.web.routes.api.servers.server.history import ( ApiServersServerHistoryHandler, @@ -110,6 +114,11 @@ def api_handlers(handler_args): ApiServersIndexHandler, handler_args, ), + ( + r"/api/v2/servers/status/?", + ApiServersServerStatusHandler, + handler_args, + ), ( r"/api/v2/servers/([0-9]+)/?", ApiServersServerIndexHandler, diff --git a/app/classes/web/routes/api/servers/server/status.py b/app/classes/web/routes/api/servers/server/status.py new file mode 100644 index 00000000..aab501d8 --- /dev/null +++ b/app/classes/web/routes/api/servers/server/status.py @@ -0,0 +1,32 @@ +import logging +from app.classes.web.base_api_handler import BaseApiHandler + +logger = logging.getLogger(__name__) + + +class ApiServersServerStatusHandler(BaseApiHandler): + def get(self): + servers_status = [] + servers_list = self.controller.servers.get_all_servers_stats() + for server in servers_list: + if server.get("server_data").get("show_status") is True: + servers_status.append( + { + "id": server.get("server_data").get("server_id"), + "world_name": server.get("stats").get("world_name"), + "running": server.get("stats").get("running"), + "online": server.get("stats").get("online"), + "max": server.get("stats").get("max"), + "version": server.get("stats").get("version"), + "desc": server.get("stats").get("desc"), + "icon": server.get("stats").get("icon"), + } + ) + + self.finish_json( + 200, + { + "status": "ok", + "data": servers_status, + }, + ) diff --git a/app/classes/web/tornado_handler.py b/app/classes/web/tornado_handler.py index 0a7f0cb8..643a018a 100644 --- a/app/classes/web/tornado_handler.py +++ b/app/classes/web/tornado_handler.py @@ -34,7 +34,7 @@ from app.classes.web.api_handler import ( ListServers, SendCommand, ) -from app.classes.web.websocket_handler import AuthSocketHandler, PublicSocketHandler +from app.classes.web.websocket_handler import AuthSocketHandler from app.classes.web.static_handler import CustomStaticHandler from app.classes.web.upload_handler import UploadHandler from app.classes.web.http_handler import HTTPHandler, HTTPHandlerPage @@ -154,7 +154,6 @@ class Webserver: (r"/ajax/(.*)", AjaxHandler, handler_args), (r"/files/(.*)", FileHandler, handler_args), (r"/ws/auth", AuthSocketHandler, handler_args), - (r"/ws/public", PublicSocketHandler, handler_args), (r"/upload", UploadHandler, handler_args), (r"/status", StatusHandler, handler_args), # API Routes V1 diff --git a/app/classes/web/websocket_handler.py b/app/classes/web/websocket_handler.py index d15d6c7d..ae166e3a 100644 --- a/app/classes/web/websocket_handler.py +++ b/app/classes/web/websocket_handler.py @@ -176,45 +176,3 @@ class AuthSocketHandler(BaseSocketHandler): ) WebSocketManager().add_client(self) logger.debug("Opened WebSocket connection") - - -class PublicSocketHandler(BaseSocketHandler): - ws_state = EnumWebSocketState.WS_PUBLIC - ws_authorized_pages = {"404", "error", "login", "offline", "status"} - ws_authorized_events = {"update_server_status"} # Must be overridden at init - page = None - page_query_params = None - controller = None - tasks_manager = None - translator = None - io_loop = None - - def initialize( - self, helper=None, controller=None, tasks_manager=None, translator=None - ): - self.helper = helper - self.controller = controller - self.tasks_manager = tasks_manager - self.translator = translator - self.io_loop = tornado.ioloop.IOLoop.current() - - def get_user_id(self): - return None - - def check_auth(self): - return False - - # pylint: disable=arguments-differ - def open(self): - logger.debug("Checking Public WebSocket") - self.handle() - - def handle(self): - self.page = self.get_query_argument("page") - self.page_query_params = dict( - parse_qsl( - Helpers.remove_prefix(self.get_query_argument("page_query_params"), "?") - ) - ) - WebSocketManager().add_client(self) - logger.debug("Opened Public WebSocket connection") diff --git a/app/frontend/templates/panel/dashboard.html b/app/frontend/templates/panel/dashboard.html index 9aa207eb..377a109f 100644 --- a/app/frontend/templates/panel/dashboard.html +++ b/app/frontend/templates/panel/dashboard.html @@ -58,13 +58,11 @@
-

+

{{ translate('dashboard', 'cpuUsage', data['lang']) }}: {{ data.get('hosts_data').get('cpu_usage') }}

-

+

{{ translate('dashboard', 'memUsage', data['lang']) }}: {{ data.get('hosts_data').get('mem_percent') }}%

@@ -111,12 +109,9 @@ {% for item in data['hosts_data']['disk_json'] %} {% if item["mount"] in data["monitored"] %}
-

+

{{item["mount"]}}

-
+
{{item["used"]}} / + " role="progressbar" style="color: black; height: 100%; width: {{item['percent_used']}}%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">{{item["used"]}} / {{item["total"]}}
@@ -153,9 +147,7 @@ data['lang']) }} {% if len(data['servers']) > 0 %} {% if data['user_data']['hints'] %} - + {% end %} {% end %}
  {{ @@ -193,8 +185,7 @@ {% if server['alert'] %} - + {{ server['server_data']['server_name'] }}  {% else %} @@ -208,13 +199,11 @@ {% if server['user_command_permission'] %} {% if server['stats']['importing'] and server['stats']['running'] %} -  {{ translate('serverTerm', 'installing', +  {{ translate('serverTerm', 'installing', data['lang']) }} {% elif server['stats']['updating']%} -  {{ translate('serverTerm', 'updating', +  {{ translate('serverTerm', 'updating', data['lang']) }} {% elif server['stats']['waiting_start']%} @@ -226,31 +215,25 @@ {{ translate('serverTerm', 'importing', data['lang']) }} {% elif server['stats']['running'] %} - +   - +   - +   {% else %} - +   - +   - +   {% end %} @@ -258,8 +241,7 @@ -
+
+ " role="progressbar" style="width: {{server['stats']['cpu']}}%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
{{server['stats']['cpu']}}% -
+
+ " role="progressbar" style="width: {{server['stats']['mem_percent']}}%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
{{server['stats']['mem_percent']}}% - @@ -305,8 +284,7 @@ data['lang']) }}
{% if server['stats']['desc'] != 'False' %} -
{{ +
{{ server['stats']['desc'] }}

{% end %} @@ -334,16 +312,14 @@

- + {% end %}
{% for server in data['failed_servers'] %} -  {{server['server_name']}} +  {{server['server_name']}} @@ -368,28 +344,22 @@
- + {% if server['stats']['running'] %} {{ translate('dashboard', 'online', data['lang']) }} @@ -410,23 +380,17 @@ {% if server['stats']['running'] %}
@@ -452,31 +416,24 @@ {% elif server['stats']['importing']%} {% else %} @@ -488,15 +445,13 @@
-
+
{{ translate('dashboard', 'cpuUsage', data['lang']) }}
-
+
+ " role="progressbar" style="width: {{server['stats']['cpu']}}%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
{{server['stats']['cpu']}}%
@@ -514,8 +468,7 @@
{{ translate('dashboard', 'memUsage', data['lang']) }}
-
+
+ " role="progressbar" style="width: {{server['stats']['mem_percent']}}%" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
{{server['stats']['mem_percent']}}% - @@ -554,8 +506,7 @@ data['lang']) }}
{% if server['stats']['desc'] != 'False' %} -
+
{{ server['stats']['desc'] }}

{% end %} @@ -796,6 +747,7 @@ /* Update Motd */ let motd = ""; if (server.desc) { + m_motd = `` + server.desc + ``; motd = `` + server.desc + ``; m_server_infos = server_infos + '
' + motd + '
' + "
"; server_infos = server_infos + '
' + motd + '
' + "
"; diff --git a/app/frontend/templates/public/status.html b/app/frontend/templates/public/status.html index b93c0479..4d99f7a6 100644 --- a/app/frontend/templates/public/status.html +++ b/app/frontend/templates/public/status.html @@ -44,9 +44,14 @@ {% if server['stats']['desc'] != 'False' %} - icon - {{ - server['stats']['desc'] }}
+
+
+ icon +
+
+ {{ server['stats']['desc'] }} +
+
{% end %} @@ -183,7 +188,7 @@ m_server_online_status = document.getElementById('m_server_online_status_' + server.id); /* TODO Update each element */ - if (server.int_ping_results) { + if (server.running) { /* Update Players */ if (server.players) { server_players.innerHTML = server.online + ` / ` + server.max + ` {{ translate('dashboard', 'max', data['lang']) }}
` @@ -193,16 +198,18 @@ var motd = ""; if (server.desc) { if (server.icon) { - motd = `icon `; + img_motd = `icon `; m_motd = `icon `; } else { - motd = `icon `; + img_motd = `icon `; m_motd = `icon `; } - motd = motd + `` + server.desc + `
`; + desc_motd = `` + server.desc + `
`; m_motd = m_motd + `
` + server.desc + `
`; + + motd = `
` + img_motd + `
` + desc_motd + `
`; server_motd.innerHTML = motd; m_server_motd.innerHTML = m_motd; } @@ -235,17 +242,31 @@ } function update_servers_status(data) { - console.log(data); - update_one_server_status(data[0]); + console.log("update servers"); + data.forEach(server => { + console.log(server); + update_one_server_status(server); + }); display_motd(); } + function refreshStatus() { + let xmlHttp = new XMLHttpRequest(); + xmlHttp.onreadystatechange = function () { + if (this.readyState == 4 && this.status == 200) { + var myData = JSON.parse(this.responseText); + update_servers_status(myData.data); + } + }; + xmlHttp.open('GET', '/api/v2/servers/status', true); + xmlHttp.send(); + + setTimeout(refreshStatus, 30000); + } + $(document).ready(function () { console.log("ready!"); - - if (webSocket) { - webSocket.on('update_server_status', update_servers_status); - } + refreshStatus(); }()); diff --git a/app/frontend/templates/public_base.html b/app/frontend/templates/public_base.html index 77632762..6513e4e9 100644 --- a/app/frontend/templates/public_base.html +++ b/app/frontend/templates/public_base.html @@ -55,120 +55,7 @@ - {% block js %} diff --git a/app/migrations/stats/20230827_add_icon.py b/app/migrations/stats/20230827_add_icon.py new file mode 100644 index 00000000..2d7970e8 --- /dev/null +++ b/app/migrations/stats/20230827_add_icon.py @@ -0,0 +1,16 @@ +# Generated by database migrator +import peewee + + +def migrate(migrator, database, **kwargs): + migrator.add_columns("server_stats", icon=peewee.CharField(null=True)) + """ + Write your migrations here. + """ + + +def rollback(migrator, database, **kwargs): + migrator.drop_columns("server_stats", ["icon"]) + """ + Write your rollback migrations here. + """