From c7f7b2539ca51df415c70341600616ea7a67e302 Mon Sep 17 00:00:00 2001 From: Zedifus Date: Thu, 14 Apr 2022 03:07:56 +0100 Subject: [PATCH 1/7] Reenable invalid-name checking Add naming exemptions desired by devs --- .pylintrc | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/.pylintrc b/.pylintrc index ddb05551..ba047ba8 100644 --- a/.pylintrc +++ b/.pylintrc @@ -94,7 +94,6 @@ disable=C0330, fixme, import-error, inconsistent-return-statements, - invalid-name, locally-disabled, logging-format-interpolation, logging-fstring-interpolation, @@ -236,10 +235,20 @@ function-naming-style=snake_case #function-rgx= # Good variable names which should always be accepted, separated by a comma. -good-names=i, +good-names=e, + ex, + f, + i, + id, + ip, j, k, - ex, + p, + r, + rs, + s, + tz, + v, Run, _ From 92c8fc04f3b751065e11c1650a340a96c6231610 Mon Sep 17 00:00:00 2001 From: Zedifus Date: Thu, 14 Apr 2022 03:10:25 +0100 Subject: [PATCH 2/7] =?UTF-8?q?Refactor=20to=20standardize=20class/variabl?= =?UTF-8?q?e=20naming=20=E2=9C=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/crafty_perms_controller.py | 30 +- .../controllers/management_controller.py | 40 +- app/classes/controllers/roles_controller.py | 36 +- .../controllers/server_perms_controller.py | 79 +- app/classes/controllers/servers_controller.py | 110 +- app/classes/controllers/users_controller.py | 54 +- app/classes/minecraft/bedrock_ping.py | 49 +- app/classes/minecraft/mc_ping.py | 10 +- app/classes/minecraft/server_props.py | 26 +- app/classes/minecraft/serverjars.py | 47 +- app/classes/minecraft/stats.py | 32 +- app/classes/models/crafty_permissions.py | 126 ++- app/classes/models/management.py | 71 +- app/classes/models/roles.py | 4 +- app/classes/models/server_permissions.py | 136 ++- app/classes/models/servers.py | 102 +- app/classes/models/users.py | 44 +- app/classes/shared/authentication.py | 6 +- app/classes/shared/command.py | 4 +- app/classes/shared/console.py | 24 +- app/classes/shared/file_helpers.py | 12 +- app/classes/shared/helpers.py | 110 +- app/classes/shared/import3.py | 6 +- app/classes/shared/installer.py | 4 +- app/classes/shared/main_controller.py | 215 ++-- app/classes/shared/main_models.py | 7 +- app/classes/shared/migration.py | 966 +++++++++--------- app/classes/shared/permission_helper.py | 15 +- app/classes/shared/server.py | 178 ++-- app/classes/shared/tasks.py | 74 +- app/classes/web/ajax_handler.py | 55 +- app/classes/web/api_handler.py | 26 +- app/classes/web/default_handler.py | 3 +- app/classes/web/file_handler.py | 84 +- app/classes/web/panel_handler.py | 130 +-- app/classes/web/public_handler.py | 6 +- app/classes/web/server_handler.py | 30 +- app/classes/web/tornado_handler.py | 22 +- app/classes/web/upload_handler.py | 10 +- app/classes/web/websocket_helper.py | 5 +- main.py | 14 +- 41 files changed, 1501 insertions(+), 1501 deletions(-) diff --git a/app/classes/controllers/crafty_perms_controller.py b/app/classes/controllers/crafty_perms_controller.py index cee677da..04072784 100644 --- a/app/classes/controllers/crafty_perms_controller.py +++ b/app/classes/controllers/crafty_perms_controller.py @@ -1,37 +1,37 @@ import logging from app.classes.models.crafty_permissions import ( - Permissions_Crafty, - Enum_Permissions_Crafty, + PermissionsCrafty, + EnumPermissionsCrafty, ) from app.classes.models.users import ApiKeys logger = logging.getLogger(__name__) -class Crafty_Perms_Controller: +class CraftyPermsController: @staticmethod def list_defined_crafty_permissions(): - permissions_list = Permissions_Crafty.get_permissions_list() + permissions_list = PermissionsCrafty.get_permissions_list() return permissions_list @staticmethod def get_mask_crafty_permissions(user_id): - permissions_mask = Permissions_Crafty.get_crafty_permissions_mask(user_id) + permissions_mask = PermissionsCrafty.get_crafty_permissions_mask(user_id) return permissions_mask @staticmethod def set_permission( - permission_mask, permission_tested: Enum_Permissions_Crafty, value + permission_mask, permission_tested: EnumPermissionsCrafty, value ): - return Permissions_Crafty.set_permission( + return PermissionsCrafty.set_permission( permission_mask, permission_tested, value ) @staticmethod def can_create_server(user_id): - return Permissions_Crafty.can_add_in_crafty( - user_id, Enum_Permissions_Crafty.Server_Creation + return PermissionsCrafty.can_add_in_crafty( + user_id, EnumPermissionsCrafty.SERVER_CREATION ) @staticmethod @@ -52,22 +52,22 @@ class Crafty_Perms_Controller: @staticmethod def list_all_crafty_permissions_quantity_limits(): - return Permissions_Crafty.get_all_permission_quantity_list() + return PermissionsCrafty.get_all_permission_quantity_list() @staticmethod def list_crafty_permissions_quantity_limits(user_id): - return Permissions_Crafty.get_permission_quantity_list(user_id) + return PermissionsCrafty.get_permission_quantity_list(user_id) @staticmethod def get_crafty_permissions_list(user_id): - permissions_mask = Permissions_Crafty.get_crafty_permissions_mask(user_id) - permissions_list = Permissions_Crafty.get_permissions(permissions_mask) + permissions_mask = PermissionsCrafty.get_crafty_permissions_mask(user_id) + permissions_list = PermissionsCrafty.get_permissions(permissions_mask) return permissions_list @staticmethod def add_server_creation(user_id): - return Permissions_Crafty.add_server_creation(user_id) + return PermissionsCrafty.add_server_creation(user_id) @staticmethod def get_api_key_permissions_list(key: ApiKeys): - return Permissions_Crafty.get_api_key_permissions_list(key) + return PermissionsCrafty.get_api_key_permissions_list(key) diff --git a/app/classes/controllers/management_controller.py b/app/classes/controllers/management_controller.py index 5aa59cf8..099dbf0d 100644 --- a/app/classes/controllers/management_controller.py +++ b/app/classes/controllers/management_controller.py @@ -1,12 +1,12 @@ import logging -from app.classes.models.management import helpers_management -from app.classes.models.servers import helper_servers +from app.classes.models.management import HelpersManagement +from app.classes.models.servers import HelperServers logger = logging.getLogger(__name__) -class Management_Controller: +class ManagementController: def __init__(self, management_helper): self.management_helper = management_helper @@ -15,17 +15,17 @@ class Management_Controller: # ********************************************************************************** @staticmethod def get_latest_hosts_stats(): - return helpers_management.get_latest_hosts_stats() + return HelpersManagement.get_latest_hosts_stats() # ********************************************************************************** # Commands Methods # ********************************************************************************** @staticmethod def get_unactioned_commands(): - return helpers_management.get_unactioned_commands() + return HelpersManagement.get_unactioned_commands() def send_command(self, user_id, server_id, remote_ip, command): - server_name = helper_servers.get_server_friendly_name(server_id) + server_name = HelperServers.get_server_friendly_name(server_id) # Example: Admin issued command start_server for server Survival self.management_helper.add_to_audit_log( @@ -34,18 +34,18 @@ class Management_Controller: server_id, remote_ip, ) - helpers_management.add_command(server_id, user_id, remote_ip, command) + HelpersManagement.add_command(server_id, user_id, remote_ip, command) @staticmethod def mark_command_complete(command_id=None): - return helpers_management.mark_command_complete(command_id) + return HelpersManagement.mark_command_complete(command_id) # ********************************************************************************** # Audit_Log Methods # ********************************************************************************** @staticmethod def get_actity_log(): - return helpers_management.get_actity_log() + return HelpersManagement.get_actity_log() def add_to_audit_log(self, user_id, log_msg, server_id=None, source_ip=None): return self.management_helper.add_to_audit_log( @@ -71,7 +71,7 @@ class Management_Controller: comment=None, enabled=True, ): - return helpers_management.create_scheduled_task( + return HelpersManagement.create_scheduled_task( server_id, action, interval, @@ -84,42 +84,42 @@ class Management_Controller: @staticmethod def delete_scheduled_task(schedule_id): - return helpers_management.delete_scheduled_task(schedule_id) + return HelpersManagement.delete_scheduled_task(schedule_id) @staticmethod def update_scheduled_task(schedule_id, updates): - return helpers_management.update_scheduled_task(schedule_id, updates) + return HelpersManagement.update_scheduled_task(schedule_id, updates) @staticmethod def get_scheduled_task(schedule_id): - return helpers_management.get_scheduled_task(schedule_id) + return HelpersManagement.get_scheduled_task(schedule_id) @staticmethod def get_scheduled_task_model(schedule_id): - return helpers_management.get_scheduled_task_model(schedule_id) + return HelpersManagement.get_scheduled_task_model(schedule_id) @staticmethod def get_child_schedules(sch_id): - return helpers_management.get_child_schedules(sch_id) + return HelpersManagement.get_child_schedules(sch_id) @staticmethod def get_schedules_by_server(server_id): - return helpers_management.get_schedules_by_server(server_id) + return HelpersManagement.get_schedules_by_server(server_id) @staticmethod def get_schedules_all(): - return helpers_management.get_schedules_all() + return HelpersManagement.get_schedules_all() @staticmethod def get_schedules_enabled(): - return helpers_management.get_schedules_enabled() + return HelpersManagement.get_schedules_enabled() # ********************************************************************************** # Backups Methods # ********************************************************************************** @staticmethod def get_backup_config(server_id): - return helpers_management.get_backup_config(server_id) + return HelpersManagement.get_backup_config(server_id) def set_backup_config( self, @@ -135,7 +135,7 @@ class Management_Controller: @staticmethod def get_excluded_backup_dirs(server_id: int): - return helpers_management.get_excluded_backup_dirs(server_id) + return HelpersManagement.get_excluded_backup_dirs(server_id) def add_excluded_backup_dir(self, server_id: int, dir_to_add: str): self.management_helper.add_excluded_backup_dir(server_id, dir_to_add) diff --git a/app/classes/controllers/roles_controller.py b/app/classes/controllers/roles_controller.py index 90a357f1..266bb658 100644 --- a/app/classes/controllers/roles_controller.py +++ b/app/classes/controllers/roles_controller.py @@ -1,34 +1,34 @@ import logging -from app.classes.models.roles import helper_roles -from app.classes.models.server_permissions import Permissions_Servers +from app.classes.models.roles import HelperRoles +from app.classes.models.server_permissions import PermissionsServers from app.classes.shared.helpers import Helpers logger = logging.getLogger(__name__) -class Roles_Controller: +class RolesController: def __init__(self, users_helper, roles_helper): self.users_helper = users_helper self.roles_helper = roles_helper @staticmethod def get_all_roles(): - return helper_roles.get_all_roles() + return HelperRoles.get_all_roles() @staticmethod def get_roleid_by_name(role_name): - return helper_roles.get_roleid_by_name(role_name) + return HelperRoles.get_roleid_by_name(role_name) @staticmethod def get_role(role_id): - return helper_roles.get_role(role_id) + return HelperRoles.get_role(role_id) @staticmethod def update_role(role_id: str, role_data=None, permissions_mask: str = "00000000"): if role_data is None: role_data = {} - base_data = Roles_Controller.get_role_with_servers(role_id) + base_data = RolesController.get_role_with_servers(role_id) up_data = {} added_servers = set() removed_servers = set() @@ -45,37 +45,35 @@ class Roles_Controller: f"role: {role_data} +server:{added_servers} -server{removed_servers}" ) for server in added_servers: - Permissions_Servers.get_or_create(role_id, server, permissions_mask) + PermissionsServers.get_or_create(role_id, server, permissions_mask) for server in base_data["servers"]: - Permissions_Servers.update_role_permission( - role_id, server, permissions_mask - ) + PermissionsServers.update_role_permission(role_id, server, permissions_mask) # TODO: This is horribly inefficient and we should be using bulk queries # but im going for functionality at this point - Permissions_Servers.delete_roles_permissions(role_id, removed_servers) + PermissionsServers.delete_roles_permissions(role_id, removed_servers) if up_data: - helper_roles.update_role(role_id, up_data) + HelperRoles.update_role(role_id, up_data) @staticmethod def add_role(role_name): - return helper_roles.add_role(role_name) + return HelperRoles.add_role(role_name) def remove_role(self, role_id): - role_data = Roles_Controller.get_role_with_servers(role_id) - Permissions_Servers.delete_roles_permissions(role_id, role_data["servers"]) + role_data = RolesController.get_role_with_servers(role_id) + PermissionsServers.delete_roles_permissions(role_id, role_data["servers"]) self.users_helper.remove_roles_from_role_id(role_id) return self.roles_helper.remove_role(role_id) @staticmethod def role_id_exists(role_id): - return helper_roles.role_id_exists(role_id) + return HelperRoles.role_id_exists(role_id) @staticmethod def get_role_with_servers(role_id): - role = helper_roles.get_role(role_id) + role = HelperRoles.get_role(role_id) if role: - servers_query = Permissions_Servers.get_servers_from_role(role_id) + servers_query = PermissionsServers.get_servers_from_role(role_id) # TODO: this query needs to be narrower servers = set() for s in servers_query: diff --git a/app/classes/controllers/server_perms_controller.py b/app/classes/controllers/server_perms_controller.py index a2e422aa..f417837a 100644 --- a/app/classes/controllers/server_perms_controller.py +++ b/app/classes/controllers/server_perms_controller.py @@ -1,53 +1,53 @@ import logging from app.classes.models.server_permissions import ( - Permissions_Servers, - Enum_Permissions_Server, + PermissionsServers, + EnumPermissionsServer, ) -from app.classes.models.users import helper_users, ApiKeys -from app.classes.models.roles import helper_roles -from app.classes.models.servers import helper_servers -from app.classes.shared.main_models import db_shortcuts +from app.classes.models.users import HelperUsers, ApiKeys +from app.classes.models.roles import HelperRoles +from app.classes.models.servers import HelperServers +from app.classes.shared.main_models import DatabaseShortcuts logger = logging.getLogger(__name__) -class Server_Perms_Controller: +class ServerPermsController: @staticmethod def get_server_user_list(server_id): - return Permissions_Servers.get_server_user_list(server_id) + return PermissionsServers.get_server_user_list(server_id) @staticmethod def list_defined_permissions(): - permissions_list = Permissions_Servers.get_permissions_list() + permissions_list = PermissionsServers.get_permissions_list() return permissions_list @staticmethod def get_mask_permissions(role_id, server_id): - permissions_mask = Permissions_Servers.get_permissions_mask(role_id, server_id) + permissions_mask = PermissionsServers.get_permissions_mask(role_id, server_id) return permissions_mask @staticmethod def get_role_permissions(role_id): - permissions_list = Permissions_Servers.get_role_permissions_list(role_id) + permissions_list = PermissionsServers.get_role_permissions_list(role_id) return permissions_list @staticmethod def add_role_server(server_id, role_id, rs_permissions="00000000"): - return Permissions_Servers.add_role_server(server_id, role_id, rs_permissions) + return PermissionsServers.add_role_server(server_id, role_id, rs_permissions) @staticmethod def get_server_roles(server_id): - return Permissions_Servers.get_server_roles(server_id) + return PermissionsServers.get_server_roles(server_id) @staticmethod def backup_role_swap(old_server_id, new_server_id): - role_list = Permissions_Servers.get_server_roles(old_server_id) + role_list = PermissionsServers.get_server_roles(old_server_id) for role in role_list: - Permissions_Servers.add_role_server( + PermissionsServers.add_role_server( new_server_id, role.role_id, - Permissions_Servers.get_permissions_mask( + PermissionsServers.get_permissions_mask( int(role.role_id), int(old_server_id) ), ) @@ -60,57 +60,62 @@ class Server_Perms_Controller: # ********************************************************************************** @staticmethod def get_permissions_mask(role_id, server_id): - return Permissions_Servers.get_permissions_mask(role_id, server_id) + return PermissionsServers.get_permissions_mask(role_id, server_id) @staticmethod def set_permission( - permission_mask, permission_tested: Enum_Permissions_Server, value + permission_mask, permission_tested: EnumPermissionsServer, value ): - return Permissions_Servers.set_permission( + return PermissionsServers.set_permission( permission_mask, permission_tested, value ) @staticmethod def get_role_permissions_list(role_id): - return Permissions_Servers.get_role_permissions_list(role_id) + return PermissionsServers.get_role_permissions_list(role_id) @staticmethod def get_user_id_permissions_list(user_id: str, server_id: str): - return Permissions_Servers.get_user_id_permissions_list(user_id, server_id) + return PermissionsServers.get_user_id_permissions_list(user_id, server_id) @staticmethod def get_api_key_id_permissions_list(key_id: str, server_id: str): - key = helper_users.get_user_api_key(key_id) - return Permissions_Servers.get_api_key_permissions_list(key, server_id) + key = HelperUsers.get_user_api_key(key_id) + return PermissionsServers.get_api_key_permissions_list(key, server_id) @staticmethod def get_api_key_permissions_list(key: ApiKeys, server_id: str): - return Permissions_Servers.get_api_key_permissions_list(key, server_id) + return PermissionsServers.get_api_key_permissions_list(key, server_id) @staticmethod def get_authorized_servers_stats_from_roles(user_id): - user_roles = helper_users.get_user_roles_id(user_id) + user_roles = HelperUsers.get_user_roles_id(user_id) roles_list = [] role_server = [] authorized_servers = [] server_data = [] - for u in user_roles: - roles_list.append(helper_roles.get_role(u.role_id)) + for user in user_roles: + roles_list.append(HelperRoles.get_role(user.role_id)) - for r in roles_list: - role_test = Permissions_Servers.get_role_servers_from_role_id( - r.get("role_id") + for role in roles_list: + role_test = PermissionsServers.get_role_servers_from_role_id( + role.get("role_id") ) - for t in role_test: - role_server.append(t) + for test in role_test: + role_server.append(test) - for s in role_server: - authorized_servers.append(helper_servers.get_server_data_by_id(s.server_id)) + for server in role_server: + authorized_servers.append( + HelperServers.get_server_data_by_id(server.server_id) + ) - for s in authorized_servers: - latest = helper_servers.get_latest_server_stats(s.get("server_id")) + for server in authorized_servers: + latest = HelperServers.get_latest_server_stats(server.get("server_id")) server_data.append( - {"server_data": s, "stats": db_shortcuts.return_rows(latest)[0]} + { + "server_data": server, + "stats": DatabaseShortcuts.return_rows(latest)[0], + } ) return server_data diff --git a/app/classes/controllers/servers_controller.py b/app/classes/controllers/servers_controller.py index 14124e7a..a691cec2 100644 --- a/app/classes/controllers/servers_controller.py +++ b/app/classes/controllers/servers_controller.py @@ -2,20 +2,20 @@ import os import logging import json -from app.classes.controllers.roles_controller import Roles_Controller -from app.classes.models.servers import helper_servers -from app.classes.models.users import helper_users, ApiKeys +from app.classes.controllers.roles_controller import RolesController +from app.classes.models.servers import HelperServers +from app.classes.models.users import HelperUsers, ApiKeys from app.classes.models.server_permissions import ( - Permissions_Servers, - Enum_Permissions_Server, + PermissionsServers, + EnumPermissionsServer, ) from app.classes.shared.helpers import Helpers -from app.classes.shared.main_models import db_shortcuts +from app.classes.shared.main_models import DatabaseShortcuts logger = logging.getLogger(__name__) -class Servers_Controller: +class ServersController: def __init__(self, servers_helper): self.servers_helper = servers_helper @@ -50,80 +50,82 @@ class Servers_Controller: @staticmethod def get_server_obj(server_id): - return helper_servers.get_server_obj(server_id) + return HelperServers.get_server_obj(server_id) @staticmethod def update_server(server_obj): - return helper_servers.update_server(server_obj) + return HelperServers.update_server(server_obj) @staticmethod def set_download(server_id): - return helper_servers.set_download(server_id) + return HelperServers.set_download(server_id) @staticmethod def finish_download(server_id): - return helper_servers.finish_download(server_id) + return HelperServers.finish_download(server_id) @staticmethod def get_download_status(server_id): - return helper_servers.get_download_status(server_id) + return HelperServers.get_download_status(server_id) def remove_server(self, server_id): - roles_list = Permissions_Servers.get_roles_from_server(server_id) + roles_list = PermissionsServers.get_roles_from_server(server_id) for role in roles_list: role_id = role.role_id - role_data = Roles_Controller.get_role_with_servers(role_id) + role_data = RolesController.get_role_with_servers(role_id) role_data["servers"] = {server_id} - Permissions_Servers.delete_roles_permissions(role_id, role_data["servers"]) - Permissions_Servers.remove_roles_of_server(server_id) + PermissionsServers.delete_roles_permissions(role_id, role_data["servers"]) + PermissionsServers.remove_roles_of_server(server_id) self.servers_helper.remove_server(server_id) @staticmethod def get_server_data_by_id(server_id): - return helper_servers.get_server_data_by_id(server_id) + return HelperServers.get_server_data_by_id(server_id) # ********************************************************************************** # Servers Methods # ********************************************************************************** @staticmethod def get_all_defined_servers(): - return helper_servers.get_all_defined_servers() + return HelperServers.get_all_defined_servers() @staticmethod def get_authorized_servers(user_id): server_data = [] - user_roles = helper_users.user_role_query(user_id) - for us in user_roles: - role_servers = Permissions_Servers.get_role_servers_from_role_id(us.role_id) + user_roles = HelperUsers.user_role_query(user_id) + for user in user_roles: + role_servers = PermissionsServers.get_role_servers_from_role_id( + user.role_id + ) for role in role_servers: - server_data.append(helper_servers.get_server_data_by_id(role.server_id)) + server_data.append(HelperServers.get_server_data_by_id(role.server_id)) return server_data @staticmethod def get_all_servers_stats(): - return helper_servers.get_all_servers_stats() + return HelperServers.get_all_servers_stats() @staticmethod def get_authorized_servers_stats_api_key(api_key: ApiKeys): server_data = [] - authorized_servers = Servers_Controller.get_authorized_servers( + authorized_servers = ServersController.get_authorized_servers( api_key.user.user_id ) - for s in authorized_servers: - latest = helper_servers.get_latest_server_stats(s.get("server_id")) - key_permissions = Permissions_Servers.get_api_key_permissions_list( - api_key, s.get("server_id") + for server in authorized_servers: + latest = HelperServers.get_latest_server_stats(server.get("server_id")) + key_permissions = PermissionsServers.get_api_key_permissions_list( + api_key, server.get("server_id") ) - if Enum_Permissions_Server.Commands in key_permissions: + if EnumPermissionsServer.COMMANDS in key_permissions: user_command_permission = True else: user_command_permission = False server_data.append( { - "server_data": s, - "stats": db_shortcuts.return_rows(latest)[0], + "server_data": server, + "stats": DatabaseShortcuts.return_rows(latest)[0], "user_command_permission": user_command_permission, } ) @@ -132,22 +134,22 @@ class Servers_Controller: @staticmethod def get_authorized_servers_stats(user_id): server_data = [] - authorized_servers = Servers_Controller.get_authorized_servers(user_id) + authorized_servers = ServersController.get_authorized_servers(user_id) - for s in authorized_servers: - latest = helper_servers.get_latest_server_stats(s.get("server_id")) + for server in authorized_servers: + latest = HelperServers.get_latest_server_stats(server.get("server_id")) # TODO - user_permissions = Permissions_Servers.get_user_id_permissions_list( - user_id, s.get("server_id") + user_permissions = PermissionsServers.get_user_id_permissions_list( + user_id, server.get("server_id") ) - if Enum_Permissions_Server.Commands in user_permissions: + if EnumPermissionsServer.COMMANDS in user_permissions: user_command_permission = True else: user_command_permission = False server_data.append( { - "server_data": s, - "stats": db_shortcuts.return_rows(latest)[0], + "server_data": server, + "stats": DatabaseShortcuts.return_rows(latest)[0], "user_command_permission": user_command_permission, } ) @@ -156,28 +158,28 @@ class Servers_Controller: @staticmethod def get_server_friendly_name(server_id): - return helper_servers.get_server_friendly_name(server_id) + return HelperServers.get_server_friendly_name(server_id) # ********************************************************************************** # Servers_Stats Methods # ********************************************************************************** @staticmethod def get_server_stats_by_id(server_id): - return helper_servers.get_server_stats_by_id(server_id) + return HelperServers.get_server_stats_by_id(server_id) @staticmethod def server_id_exists(server_id): - return helper_servers.server_id_exists(server_id) + return HelperServers.server_id_exists(server_id) @staticmethod def get_server_type_by_id(server_id): - return helper_servers.get_server_type_by_id(server_id) + return HelperServers.get_server_type_by_id(server_id) @staticmethod def server_id_authorized(server_id_a, user_id): - user_roles = helper_users.user_role_query(user_id) + user_roles = HelperUsers.user_role_query(user_id) for role in user_roles: - for server_id_b in Permissions_Servers.get_role_servers_from_role_id( + for server_id_b in PermissionsServers.get_role_servers_from_role_id( role.role_id ): if str(server_id_a) == str(server_id_b.server_id): @@ -186,12 +188,12 @@ class Servers_Controller: @staticmethod def is_crashed(server_id): - return helper_servers.is_crashed(server_id) + return HelperServers.is_crashed(server_id) @staticmethod def server_id_authorized_api_key(server_id: str, api_key: ApiKeys) -> bool: # TODO - return Servers_Controller.server_id_authorized(server_id, api_key.user.user_id) + return ServersController.server_id_authorized(server_id, api_key.user.user_id) # There is no view server permission # permission_helper.both_have_perm(api_key) @@ -199,30 +201,30 @@ class Servers_Controller: return self.servers_helper.set_update(server_id, value) @staticmethod - def get_TTL_without_player(server_id): - return helper_servers.get_TTL_without_player(server_id) + def get_ttl_without_player(server_id): + return HelperServers.get_ttl_without_player(server_id) @staticmethod def can_stop_no_players(server_id, time_limit): - return helper_servers.can_stop_no_players(server_id, time_limit) + return HelperServers.can_stop_no_players(server_id, time_limit) def set_waiting_start(self, server_id, value): self.servers_helper.set_waiting_start(server_id, value) @staticmethod def get_waiting_start(server_id): - return helper_servers.get_waiting_start(server_id) + return HelperServers.get_waiting_start(server_id) @staticmethod def get_update_status(server_id): - return helper_servers.get_update_status(server_id) + return HelperServers.get_update_status(server_id) # ********************************************************************************** # Servers Helpers Methods # ********************************************************************************** @staticmethod def get_banned_players(server_id): - stats = helper_servers.get_server_stats_by_id(server_id) + stats = HelperServers.get_server_stats_by_id(server_id) server_path = stats["server_id"]["path"] path = os.path.join(server_path, "banned-players.json") @@ -239,7 +241,7 @@ class Servers_Controller: return json.loads(content) def check_for_old_logs(self): - servers = helper_servers.get_all_defined_servers() + servers = HelperServers.get_all_defined_servers() for server in servers: logs_path = os.path.split(server["log_path"])[0] latest_log_file = os.path.split(server["log_path"])[1] diff --git a/app/classes/controllers/users_controller.py b/app/classes/controllers/users_controller.py index 0a7d1f63..bce58fa9 100644 --- a/app/classes/controllers/users_controller.py +++ b/app/classes/controllers/users_controller.py @@ -1,16 +1,16 @@ import logging from typing import Optional -from app.classes.models.users import helper_users +from app.classes.models.users import HelperUsers from app.classes.models.crafty_permissions import ( - Permissions_Crafty, - Enum_Permissions_Crafty, + PermissionsCrafty, + EnumPermissionsCrafty, ) logger = logging.getLogger(__name__) -class Users_Controller: +class UsersController: def __init__(self, helper, users_helper, authentication): self.helper = helper self.users_helper = users_helper @@ -21,42 +21,42 @@ class Users_Controller: # ********************************************************************************** @staticmethod def get_all_users(): - return helper_users.get_all_users() + return HelperUsers.get_all_users() @staticmethod def get_id_by_name(username): - return helper_users.get_user_id_by_name(username) + return HelperUsers.get_user_id_by_name(username) @staticmethod def get_user_lang_by_id(user_id): - return helper_users.get_user_lang_by_id(user_id) + return HelperUsers.get_user_lang_by_id(user_id) @staticmethod def get_user_by_id(user_id): - return helper_users.get_user(user_id) + return HelperUsers.get_user(user_id) @staticmethod def update_server_order(user_id, user_server_order): - helper_users.update_server_order(user_id, user_server_order) + HelperUsers.update_server_order(user_id, user_server_order) @staticmethod def get_server_order(user_id): - return helper_users.get_server_order(user_id) + return HelperUsers.get_server_order(user_id) @staticmethod def user_query(user_id): - return helper_users.user_query(user_id) + return HelperUsers.user_query(user_id) @staticmethod def set_support_path(user_id, support_path): - helper_users.set_support_path(user_id, support_path) + HelperUsers.set_support_path(user_id, support_path) def update_user(self, user_id: str, user_data=None, user_crafty_data=None): if user_crafty_data is None: user_crafty_data = {} if user_data is None: user_data = {} - base_data = helper_users.get_user(user_id) + base_data = HelperUsers.get_user(user_id) up_data = {} added_roles = set() removed_roles = set() @@ -76,26 +76,26 @@ class Users_Controller: up_data["hints"] = user_data["hints"] logger.debug(f"user: {user_data} +role:{added_roles} -role:{removed_roles}") for role in added_roles: - helper_users.get_or_create(user_id=user_id, role_id=role) + HelperUsers.get_or_create(user_id=user_id, role_id=role) permissions_mask = user_crafty_data.get("permissions_mask", "000") if "server_quantity" in user_crafty_data: limit_server_creation = user_crafty_data["server_quantity"][ - Enum_Permissions_Crafty.Server_Creation.name + EnumPermissionsCrafty.SERVER_CREATION.name ] limit_user_creation = user_crafty_data["server_quantity"][ - Enum_Permissions_Crafty.User_Config.name + EnumPermissionsCrafty.USER_CONFIG.name ] limit_role_creation = user_crafty_data["server_quantity"][ - Enum_Permissions_Crafty.Roles_Config.name + EnumPermissionsCrafty.ROLES_CONFIG.name ] else: limit_server_creation = 0 limit_user_creation = 0 limit_role_creation = 0 - Permissions_Crafty.add_or_update_user( + PermissionsCrafty.add_or_update_user( user_id, permissions_mask, limit_server_creation, @@ -131,7 +131,7 @@ class Users_Controller: enabled: bool = True, superuser: bool = False, ): - return helper_users.add_rawpass_user( + return HelperUsers.add_rawpass_user( username, password=password, email=email, @@ -144,15 +144,15 @@ class Users_Controller: @staticmethod def user_id_exists(user_id): - return helper_users.user_id_exists(user_id) + return HelperUsers.user_id_exists(user_id) @staticmethod def set_prepare(user_id): - return helper_users.set_prepare(user_id) + return HelperUsers.set_prepare(user_id) @staticmethod def stop_prepare(user_id): - return helper_users.stop_prepare(user_id) + return HelperUsers.stop_prepare(user_id) def get_user_id_by_api_token(self, token: str) -> str: token_data = self.authentication.check_no_iat(token) @@ -172,11 +172,11 @@ class Users_Controller: @staticmethod def get_user_roles_id(user_id): - return helper_users.get_user_roles_id(user_id) + return HelperUsers.get_user_roles_id(user_id) @staticmethod def get_user_roles_names(user_id): - return helper_users.get_user_roles_names(user_id) + return HelperUsers.get_user_roles_names(user_id) def add_role_to_user(self, user_id, role_id): return self.users_helper.add_role_to_user(user_id, role_id) @@ -186,7 +186,7 @@ class Users_Controller: @staticmethod def user_role_query(user_id): - return helper_users.user_role_query(user_id) + return HelperUsers.user_role_query(user_id) # ********************************************************************************** # Api Keys Methods @@ -194,11 +194,11 @@ class Users_Controller: @staticmethod def get_user_api_keys(user_id: str): - return helper_users.get_user_api_keys(user_id) + return HelperUsers.get_user_api_keys(user_id) @staticmethod def get_user_api_key(key_id: str): - return helper_users.get_user_api_key(key_id) + return HelperUsers.get_user_api_key(key_id) def add_user_api_key( self, diff --git a/app/classes/minecraft/bedrock_ping.py b/app/classes/minecraft/bedrock_ping.py index c1d44a35..556a221a 100644 --- a/app/classes/minecraft/bedrock_ping.py +++ b/app/classes/minecraft/bedrock_ping.py @@ -37,34 +37,45 @@ class BedrockPing: @staticmethod def __slice(in_bytes, pattern): ret = [] - bi = 0 # bytes index - pi = 0 # pattern index - while bi < len(in_bytes): + bytes_index = 0 + pattern_index = 0 + while bytes_index < len(in_bytes): try: - f = BedrockPing.fields[pattern[pi]] + field = BedrockPing.fields[pattern[pattern_index]] except IndexError as index_error: raise IndexError( "Ran out of pattern with additional bytes remaining" ) from index_error - if pattern[pi] == "string": - shl = f[0] # string header length - sl = int.from_bytes( - in_bytes[bi : bi + shl], BedrockPing.byte_order, signed=f[1] - ) # string length - l = shl + sl - ret.append(in_bytes[bi + shl : bi + shl + sl].decode("ascii")) - elif pattern[pi] == "magic": - l = f[0] # length of field - ret.append(in_bytes[bi : bi + l]) + if pattern[pattern_index] == "string": + string_header_length = field[0] + string_length = int.from_bytes( + in_bytes[bytes_index : bytes_index + string_header_length], + BedrockPing.byte_order, + signed=field[1], + ) + length = string_header_length + string_length + ret.append( + in_bytes[ + bytes_index + + string_header_length : bytes_index + + string_header_length + + string_length + ].decode("ascii") + ) + elif pattern[pattern_index] == "magic": + length = field[0] + ret.append(in_bytes[bytes_index : bytes_index + length]) else: - l = f[0] # length of field + length = field[0] ret.append( int.from_bytes( - in_bytes[bi : bi + l], BedrockPing.byte_order, signed=f[1] + in_bytes[bytes_index : bytes_index + length], + BedrockPing.byte_order, + signed=field[1], ) ) - bi += l - pi += 1 + bytes_index += length + pattern_index += 1 return ret @staticmethod @@ -115,6 +126,6 @@ class BedrockPing: return self.__recvpong() except ValueError as e: print( - f"E: {e}, checking next packet. Retries remaining: {rtr}/{retries}" + f"E: {e}, checking next packet. Retries remaining: {rtr}/{retries}" ) rtr -= 1 diff --git a/app/classes/minecraft/mc_ping.py b/app/classes/minecraft/mc_ping.py index c15eabcf..1693ca41 100644 --- a/app/classes/minecraft/mc_ping.py +++ b/app/classes/minecraft/mc_ping.py @@ -78,8 +78,8 @@ class Players(list): def report(self): players = [] - for x in self: - players.append(str(x)) + for player in self: + players.append(str(player)) r_data = {"online": self.online, "max": self.max, "players": players} @@ -179,11 +179,11 @@ def ping(ip, port): # For the rest of requests see wiki.vg/Protocol def ping_bedrock(ip, port): - rd = random.Random() + rand = random.Random() try: # pylint: disable=consider-using-f-string - rd.seed("".join(re.findall("..", "%012x" % uuid.getnode()))) - client_guid = uuid.UUID(int=rd.getrandbits(32)).int + rand.seed("".join(re.findall("..", "%012x" % uuid.getnode()))) + client_guid = uuid.UUID(int=rand.getrandbits(32)).int except: client_guid = 0 try: diff --git a/app/classes/minecraft/server_props.py b/app/classes/minecraft/server_props.py index 84b8d039..834810e8 100644 --- a/app/classes/minecraft/server_props.py +++ b/app/classes/minecraft/server_props.py @@ -9,25 +9,25 @@ class ServerProps: def _parse(self): # Loads and parses the file specified in self.filepath - with open(self.filepath, encoding="utf-8") as fp: - line = fp.readline() - d = {} + with open(self.filepath, encoding="utf-8") as full_path: + line = full_path.readline() + dictionary = {} if os.path.exists(".header"): os.remove(".header") while line: if "#" != line[0]: - s = line - s1 = s[: s.find("=")] - if "\n" in s: - s2 = s[s.find("=") + 1 : s.find("\n")] + string = line + string1 = string[: string.find("=")] + if "\n" in string: + string2 = string[string.find("=") + 1 : string.find("\n")] else: - s2 = s[s.find("=") + 1 :] - d[s1] = s2 + string2 = string[string.find("=") + 1 :] + dictionary[string1] = string2 else: - with open(".header", "a+", encoding="utf-8") as h: - h.write(line) - line = fp.readline() - return d + with open(".header", "a+", encoding="utf-8") as header: + header.write(line) + line = full_path.readline() + return dictionary def print(self): # Prints the properties dictionary (using pprint) diff --git a/app/classes/minecraft/serverjars.py b/app/classes/minecraft/serverjars.py index c6b39607..380bfde8 100644 --- a/app/classes/minecraft/serverjars.py +++ b/app/classes/minecraft/serverjars.py @@ -6,8 +6,8 @@ import logging from datetime import datetime import requests -from app.classes.controllers.servers_controller import Servers_Controller -from app.classes.models.server_permissions import Permissions_Servers +from app.classes.controllers.servers_controller import ServersController +from app.classes.models.server_permissions import PermissionsServers logger = logging.getLogger(__name__) @@ -21,16 +21,16 @@ class ServerJars: full_url = f"{self.base_url}{call_url}" try: - r = requests.get(full_url, timeout=2) + response = requests.get(full_url, timeout=2) - if r.status_code not in [200, 201]: + if response.status_code not in [200, 201]: return {} except Exception as e: logger.error(f"Unable to connect to serverjar.com api due to error: {e}") return {} try: - api_data = json.loads(r.content) + api_data = json.loads(response.content) except Exception as e: logger.error(f"Unable to parse serverjar.com api result due to error: {e}") return {} @@ -60,37 +60,14 @@ class ServerJars: data = self._read_cache() return data.get("servers") - def get_serverjar_data_sorted(self): - data = self.get_serverjar_data() - - def str_to_int(x, counter=0): - try: - return ord(x[0]) + str_to_int(x[1:], counter + 1) + len(x) - except IndexError: - return 0 - - def to_int(x): - try: - return int(x) - except ValueError: - temp = x.split("-") - return to_int(temp[0]) + str_to_int(temp[1]) / 100000 - - sort_key_fn = lambda x: [to_int(y) for y in x.split(".")] - - for key in data.keys(): - data[key] = sorted(data[key], key=sort_key_fn) - - return data - def _check_api_alive(self): logger.info("Checking serverjars.com API status") check_url = f"{self.base_url}/api/fetchTypes" try: - r = requests.get(check_url, timeout=2) + response = requests.get(check_url, timeout=2) - if r.status_code in [200, 201]: + if response.status_code in [200, 201]: logger.info("Serverjars.com API is alive") return True except Exception as e: @@ -170,13 +147,13 @@ class ServerJars: # delaying download for server register to finish time.sleep(3) fetch_url = f"{self.base_url}/api/fetchJar/{server}/{version}" - server_users = Permissions_Servers.get_server_user_list(server_id) + server_users = PermissionsServers.get_server_user_list(server_id) # We need to make sure the server is registered before # we submit a db update for it's stats. while True: try: - Servers_Controller.set_download(server_id) + ServersController.set_download(server_id) for user in server_users: self.helper.websocket_helper.broadcast_user( user, "send_start_reload", {} @@ -191,7 +168,7 @@ class ServerJars: try: with open(path, "wb") as output: shutil.copyfileobj(r.raw, output) - Servers_Controller.finish_download(server_id) + ServersController.finish_download(server_id) for user in server_users: self.helper.websocket_helper.broadcast_user( @@ -204,8 +181,8 @@ class ServerJars: return True except Exception as e: logger.error(f"Unable to save jar to {path} due to error:{e}") - Servers_Controller.finish_download(server_id) - server_users = Permissions_Servers.get_server_user_list(server_id) + ServersController.finish_download(server_id) + server_users = PermissionsServers.get_server_user_list(server_id) for user in server_users: self.helper.websocket_helper.broadcast_user( user, "notification", "Executable download finished" diff --git a/app/classes/minecraft/stats.py b/app/classes/minecraft/stats.py index fa1504a3..ff861854 100644 --- a/app/classes/minecraft/stats.py +++ b/app/classes/minecraft/stats.py @@ -5,8 +5,8 @@ import base64 import psutil from app.classes.minecraft.mc_ping import ping -from app.classes.models.management import Host_Stats -from app.classes.models.servers import helper_servers +from app.classes.models.management import HostStats +from app.classes.models.servers import HelperServers from app.classes.shared.helpers import Helpers logger = logging.getLogger(__name__) @@ -121,7 +121,7 @@ class Stats: def get_server_players(self, server_id): - server = helper_servers.get_server_data_by_id(server_id) + server = HelperServers.get_server_data_by_id(server_id) logger.info(f"Getting players for server {server}") @@ -134,7 +134,7 @@ class Stats: server_port = server["server_port"] logger.debug(f"Pinging {internal_ip} on port {server_port}") - if helper_servers.get_server_type_by_id(server_id) != "minecraft-bedrock": + if HelperServers.get_server_type_by_id(server_id) != "minecraft-bedrock": int_mc_ping = ping(internal_ip, int(server_port)) ping_data = {} @@ -174,7 +174,7 @@ class Stats: return ping_data @staticmethod - def parse_server_RakNet_ping(ping_obj: object): + def parse_server_raknet_ping(ping_obj: object): try: server_icon = base64.encodebytes(ping_obj["icon"]) @@ -196,17 +196,17 @@ class Stats: stats_to_send = self.get_node_stats() node_stats = stats_to_send.get("node_stats") - Host_Stats.insert( + HostStats.insert( { - Host_Stats.boot_time: node_stats.get("boot_time", "Unknown"), - Host_Stats.cpu_usage: round(node_stats.get("cpu_usage", 0), 2), - Host_Stats.cpu_cores: node_stats.get("cpu_count", 0), - Host_Stats.cpu_cur_freq: node_stats.get("cpu_cur_freq", 0), - Host_Stats.cpu_max_freq: node_stats.get("cpu_max_freq", 0), - Host_Stats.mem_usage: node_stats.get("mem_usage", "0 MB"), - Host_Stats.mem_percent: node_stats.get("mem_percent", 0), - Host_Stats.mem_total: node_stats.get("mem_total", "0 MB"), - Host_Stats.disk_json: node_stats.get("disk_data", "{}"), + HostStats.boot_time: node_stats.get("boot_time", "Unknown"), + HostStats.cpu_usage: round(node_stats.get("cpu_usage", 0), 2), + HostStats.cpu_cores: node_stats.get("cpu_count", 0), + HostStats.cpu_cur_freq: node_stats.get("cpu_cur_freq", 0), + HostStats.cpu_max_freq: node_stats.get("cpu_max_freq", 0), + HostStats.mem_usage: node_stats.get("mem_usage", "0 MB"), + HostStats.mem_percent: node_stats.get("mem_percent", 0), + HostStats.mem_total: node_stats.get("mem_total", "0 MB"), + HostStats.disk_json: node_stats.get("disk_data", "{}"), } ).execute() @@ -239,7 +239,7 @@ class Stats: now = datetime.datetime.now() last_week = now.day - max_age - Host_Stats.delete().where(Host_Stats.time < last_week).execute() + HostStats.delete().where(HostStats.time < last_week).execute() # Server_Stats.delete().where(Server_Stats.created < last_week).execute() diff --git a/app/classes/models/crafty_permissions.py b/app/classes/models/crafty_permissions.py index a35d4f50..5d4f0461 100644 --- a/app/classes/models/crafty_permissions.py +++ b/app/classes/models/crafty_permissions.py @@ -8,7 +8,7 @@ from peewee import ( ) from app.classes.models.base_model import BaseModel -from app.classes.models.users import Users, ApiKeys, helper_users +from app.classes.models.users import Users, ApiKeys, HelperUsers from app.classes.shared.permission_helper import PermissionHelper logger = logging.getLogger(__name__) @@ -16,7 +16,7 @@ logger = logging.getLogger(__name__) # ********************************************************************************** # User_Crafty Class # ********************************************************************************** -class User_Crafty(BaseModel): +class UserCrafty(BaseModel): user_id = ForeignKeyField(Users, backref="users_crafty") permissions = CharField(default="00000000") limit_server_creation = IntegerField(default=-1) @@ -33,33 +33,33 @@ class User_Crafty(BaseModel): # ********************************************************************************** # Crafty Permissions Class # ********************************************************************************** -class Enum_Permissions_Crafty(Enum): - Server_Creation = 0 - User_Config = 1 - Roles_Config = 2 +class EnumPermissionsCrafty(Enum): + SERVER_CREATION = 0 + USER_CONFIG = 1 + ROLES_CONFIG = 2 -class Permissions_Crafty: +class PermissionsCrafty: # ********************************************************************************** # Crafty Permissions Methods # ********************************************************************************** @staticmethod def get_permissions_list(): permissions_list = [] - for member in Enum_Permissions_Crafty.__members__.items(): + for member in EnumPermissionsCrafty.__members__.items(): permissions_list.append(member[1]) return permissions_list @staticmethod def get_permissions(permissions_mask): permissions_list = [] - for member in Enum_Permissions_Crafty.__members__.items(): - if Permissions_Crafty.has_permission(permissions_mask, member[1]): + for member in EnumPermissionsCrafty.__members__.items(): + if PermissionsCrafty.has_permission(permissions_mask, member[1]): permissions_list.append(member[1]) return permissions_list @staticmethod - def has_permission(permission_mask, permission_tested: Enum_Permissions_Crafty): + def has_permission(permission_mask, permission_tested: EnumPermissionsCrafty): result = False if permission_mask[permission_tested.value] == "1": result = True @@ -67,40 +67,40 @@ class Permissions_Crafty: @staticmethod def set_permission( - permission_mask, permission_tested: Enum_Permissions_Crafty, value + permission_mask, permission_tested: EnumPermissionsCrafty, value ): - l = list(permission_mask) - l[permission_tested.value] = str(value) - permission_mask = "".join(l) + lst = list(permission_mask) + lst[permission_tested.value] = str(value) + permission_mask = "".join(lst) return permission_mask @staticmethod - def get_permission(permission_mask, permission_tested: Enum_Permissions_Crafty): + def get_permission(permission_mask, permission_tested: EnumPermissionsCrafty): return permission_mask[permission_tested.value] @staticmethod def get_crafty_permissions_mask(user_id): permissions_mask = "" - user_crafty = Permissions_Crafty.get_User_Crafty(user_id) + user_crafty = PermissionsCrafty.get_user_crafty(user_id) permissions_mask = user_crafty.permissions return permissions_mask @staticmethod def get_all_permission_quantity_list(): quantity_list = { - Enum_Permissions_Crafty.Server_Creation.name: -1, - Enum_Permissions_Crafty.User_Config.name: -1, - Enum_Permissions_Crafty.Roles_Config.name: -1, + EnumPermissionsCrafty.SERVER_CREATION.name: -1, + EnumPermissionsCrafty.USER_CONFIG.name: -1, + EnumPermissionsCrafty.ROLES_CONFIG.name: -1, } return quantity_list @staticmethod def get_permission_quantity_list(user_id): - user_crafty = Permissions_Crafty.get_User_Crafty(user_id) + user_crafty = PermissionsCrafty.get_user_crafty(user_id) quantity_list = { - Enum_Permissions_Crafty.Server_Creation.name: user_crafty.limit_server_creation, # pylint: disable=line-too-long - Enum_Permissions_Crafty.User_Config.name: user_crafty.limit_user_creation, - Enum_Permissions_Crafty.Roles_Config.name: user_crafty.limit_role_creation, + EnumPermissionsCrafty.SERVER_CREATION.name: user_crafty.limit_server_creation, # pylint: disable=line-too-long + EnumPermissionsCrafty.USER_CONFIG.name: user_crafty.limit_user_creation, + EnumPermissionsCrafty.ROLES_CONFIG.name: user_crafty.limit_role_creation, } return quantity_list @@ -108,31 +108,29 @@ class Permissions_Crafty: # User_Crafty Methods # ********************************************************************************** @staticmethod - def get_User_Crafty(user_id): + def get_user_crafty(user_id): try: - user_crafty = ( - User_Crafty.select().where(User_Crafty.user_id == user_id).get() - ) + user_crafty = UserCrafty.select().where(UserCrafty.user_id == user_id).get() except DoesNotExist: - user_crafty = User_Crafty.insert( + user_crafty = UserCrafty.insert( { - User_Crafty.user_id: user_id, - User_Crafty.permissions: "000", - User_Crafty.limit_server_creation: 0, - User_Crafty.limit_user_creation: 0, - User_Crafty.limit_role_creation: 0, - User_Crafty.created_server: 0, - User_Crafty.created_user: 0, - User_Crafty.created_role: 0, + UserCrafty.user_id: user_id, + UserCrafty.permissions: "000", + UserCrafty.limit_server_creation: 0, + UserCrafty.limit_user_creation: 0, + UserCrafty.limit_role_creation: 0, + UserCrafty.created_server: 0, + UserCrafty.created_user: 0, + UserCrafty.created_role: 0, } ).execute() - user_crafty = Permissions_Crafty.get_User_Crafty(user_id) + user_crafty = PermissionsCrafty.get_user_crafty(user_id) return user_crafty @staticmethod def add_user_crafty(user_id, uc_permissions): - user_crafty = User_Crafty.insert( - {User_Crafty.user_id: user_id, User_Crafty.permissions: uc_permissions} + user_crafty = UserCrafty.insert( + {UserCrafty.user_id: user_id, UserCrafty.permissions: uc_permissions} ).execute() return user_crafty @@ -145,46 +143,44 @@ class Permissions_Crafty: limit_role_creation, ): try: - user_crafty = ( - User_Crafty.select().where(User_Crafty.user_id == user_id).get() - ) + user_crafty = UserCrafty.select().where(UserCrafty.user_id == user_id).get() user_crafty.permissions = permissions_mask user_crafty.limit_server_creation = limit_server_creation user_crafty.limit_user_creation = limit_user_creation user_crafty.limit_role_creation = limit_role_creation - User_Crafty.save(user_crafty) + UserCrafty.save(user_crafty) except: - User_Crafty.insert( + UserCrafty.insert( { - User_Crafty.user_id: user_id, - User_Crafty.permissions: permissions_mask, - User_Crafty.limit_server_creation: limit_server_creation, - User_Crafty.limit_user_creation: limit_user_creation, - User_Crafty.limit_role_creation: limit_role_creation, + UserCrafty.user_id: user_id, + UserCrafty.permissions: permissions_mask, + UserCrafty.limit_server_creation: limit_server_creation, + UserCrafty.limit_user_creation: limit_user_creation, + UserCrafty.limit_role_creation: limit_role_creation, } ).execute() @staticmethod def get_created_quantity_list(user_id): - user_crafty = Permissions_Crafty.get_User_Crafty(user_id) + user_crafty = PermissionsCrafty.get_user_crafty(user_id) quantity_list = { - Enum_Permissions_Crafty.Server_Creation.name: user_crafty.created_server, - Enum_Permissions_Crafty.User_Config.name: user_crafty.created_user, - Enum_Permissions_Crafty.Roles_Config.name: user_crafty.created_role, + EnumPermissionsCrafty.SERVER_CREATION.name: user_crafty.created_server, + EnumPermissionsCrafty.USER_CONFIG.name: user_crafty.created_user, + EnumPermissionsCrafty.ROLES_CONFIG.name: user_crafty.created_role, } return quantity_list @staticmethod def get_crafty_limit_value(user_id, permission): - quantity_list = Permissions_Crafty.get_permission_quantity_list(user_id) + quantity_list = PermissionsCrafty.get_permission_quantity_list(user_id) return quantity_list[permission] @staticmethod def can_add_in_crafty(user_id, permission): - user_crafty = Permissions_Crafty.get_User_Crafty(user_id) - can = Permissions_Crafty.has_permission(user_crafty.permissions, permission) - limit_list = Permissions_Crafty.get_permission_quantity_list(user_id) - quantity_list = Permissions_Crafty.get_created_quantity_list(user_id) + user_crafty = PermissionsCrafty.get_user_crafty(user_id) + can = PermissionsCrafty.has_permission(user_crafty.permissions, permission) + limit_list = PermissionsCrafty.get_permission_quantity_list(user_id) + quantity_list = PermissionsCrafty.get_created_quantity_list(user_id) return can and ( (quantity_list[permission.name] < limit_list[permission.name]) or limit_list[permission.name] == -1 @@ -192,26 +188,26 @@ class Permissions_Crafty: @staticmethod def add_server_creation(user_id): - user_crafty = Permissions_Crafty.get_User_Crafty(user_id) + user_crafty = PermissionsCrafty.get_user_crafty(user_id) user_crafty.created_server += 1 - User_Crafty.save(user_crafty) + UserCrafty.save(user_crafty) return user_crafty.created_server @staticmethod def get_api_key_permissions_list(key: ApiKeys): - user = helper_users.get_user(key.user_id) + user = HelperUsers.get_user(key.user_id) if user["superuser"] and key.superuser: - return Permissions_Crafty.get_permissions_list() + return PermissionsCrafty.get_permissions_list() else: if user["superuser"]: user_permissions_mask = "111" else: - user_permissions_mask = Permissions_Crafty.get_crafty_permissions_mask( + user_permissions_mask = PermissionsCrafty.get_crafty_permissions_mask( user["user_id"] ) key_permissions_mask: str = key.crafty_permissions permissions_mask = PermissionHelper.combine_masks( user_permissions_mask, key_permissions_mask ) - permissions_list = Permissions_Crafty.get_permissions(permissions_mask) + permissions_list = PermissionsCrafty.get_permissions(permissions_mask) return permissions_list diff --git a/app/classes/models/management.py b/app/classes/models/management.py index 27a4e8c5..7fbfc919 100644 --- a/app/classes/models/management.py +++ b/app/classes/models/management.py @@ -13,17 +13,17 @@ from peewee import ( from playhouse.shortcuts import model_to_dict from app.classes.models.base_model import BaseModel -from app.classes.models.users import Users, helper_users +from app.classes.models.users import Users, HelperUsers from app.classes.models.servers import Servers -from app.classes.models.server_permissions import Permissions_Servers -from app.classes.shared.main_models import db_shortcuts +from app.classes.models.server_permissions import PermissionsServers +from app.classes.shared.main_models import DatabaseShortcuts logger = logging.getLogger(__name__) # ********************************************************************************** # Audit_Log Class # ********************************************************************************** -class Audit_Log(BaseModel): +class AuditLog(BaseModel): audit_id = AutoField() created = DateTimeField(default=datetime.datetime.now) user_name = CharField(default="") @@ -38,7 +38,7 @@ class Audit_Log(BaseModel): # ********************************************************************************** # Host_Stats Class # ********************************************************************************** -class Host_Stats(BaseModel): +class HostStats(BaseModel): time = DateTimeField(default=datetime.datetime.now, index=True) boot_time = CharField(default="") cpu_usage = FloatField(default=0) @@ -120,7 +120,7 @@ class Backups(BaseModel): table_name = "backups" -class helpers_management: +class HelpersManagement: def __init__(self, database, helper): self.database = database self.helper = helper @@ -131,7 +131,7 @@ class helpers_management: @staticmethod def get_latest_hosts_stats(): # pylint: disable=no-member - query = Host_Stats.select().order_by(Host_Stats.id.desc()).get() + query = HostStats.select().order_by(HostStats.id.desc()).get() return model_to_dict(query) # ********************************************************************************** @@ -166,60 +166,60 @@ class helpers_management: # ********************************************************************************** @staticmethod def get_actity_log(): - q = Audit_Log.select() - return db_shortcuts.return_db_rows(q) + query = AuditLog.select() + return DatabaseShortcuts.return_db_rows(query) def add_to_audit_log(self, user_id, log_msg, server_id=None, source_ip=None): logger.debug(f"Adding to audit log User:{user_id} - Message: {log_msg} ") - user_data = helper_users.get_user(user_id) + user_data = HelperUsers.get_user(user_id) audit_msg = f"{str(user_data['username']).capitalize()} {log_msg}" - server_users = Permissions_Servers.get_server_user_list(server_id) + server_users = PermissionsServers.get_server_user_list(server_id) for user in server_users: self.helper.websocket_helper.broadcast_user(user, "notification", audit_msg) - Audit_Log.insert( + AuditLog.insert( { - Audit_Log.user_name: user_data["username"], - Audit_Log.user_id: user_id, - Audit_Log.server_id: server_id, - Audit_Log.log_msg: audit_msg, - Audit_Log.source_ip: source_ip, + AuditLog.user_name: user_data["username"], + AuditLog.user_id: user_id, + AuditLog.server_id: server_id, + AuditLog.log_msg: audit_msg, + AuditLog.source_ip: source_ip, } ).execute() # deletes records when they're more than 100 - ordered = Audit_Log.select().order_by(+Audit_Log.created) + ordered = AuditLog.select().order_by(+AuditLog.created) for item in ordered: if not self.helper.get_setting("max_audit_entries"): max_entries = 300 else: max_entries = self.helper.get_setting("max_audit_entries") - if Audit_Log.select().count() > max_entries: - Audit_Log.delete().where(Audit_Log.audit_id == item.audit_id).execute() + if AuditLog.select().count() > max_entries: + AuditLog.delete().where(AuditLog.audit_id == item.audit_id).execute() else: return def add_to_audit_log_raw(self, user_name, user_id, server_id, log_msg, source_ip): - Audit_Log.insert( + AuditLog.insert( { - Audit_Log.user_name: user_name, - Audit_Log.user_id: user_id, - Audit_Log.server_id: server_id, - Audit_Log.log_msg: log_msg, - Audit_Log.source_ip: source_ip, + AuditLog.user_name: user_name, + AuditLog.user_id: user_id, + AuditLog.server_id: server_id, + AuditLog.log_msg: log_msg, + AuditLog.source_ip: source_ip, } ).execute() # deletes records when they're more than 100 - ordered = Audit_Log.select().order_by(+Audit_Log.created) + ordered = AuditLog.select().order_by(+AuditLog.created) for item in ordered: # configurable through app/config/config.json if not self.helper.get_setting("max_audit_entries"): max_entries = 300 else: max_entries = self.helper.get_setting("max_audit_entries") - if Audit_Log.select().count() > max_entries: - Audit_Log.delete().where(Audit_Log.audit_id == item.audit_id).execute() + if AuditLog.select().count() > max_entries: + AuditLog.delete().where(AuditLog.audit_id == item.audit_id).execute() else: return @@ -363,17 +363,20 @@ class helpers_management: if not new_row: with self.database.atomic(): if backup_path is not None: - u1 = ( + server_rows = ( Servers.update(backup_path=backup_path) .where(Servers.server_id == server_id) .execute() ) else: - u1 = 0 - u2 = ( + server_rows = 0 + backup_rows = ( Backups.update(conf).where(Backups.server_id == server_id).execute() ) - logger.debug(f"Updating existing backup record. {u1}+{u2} rows affected") + logger.debug( + f"Updating existing backup record. " + f"{server_rows}+{backup_rows} rows affected" + ) else: with self.database.atomic(): conf["server_id"] = server_id @@ -386,7 +389,7 @@ class helpers_management: @staticmethod def get_excluded_backup_dirs(server_id: int): - excluded_dirs = helpers_management.get_backup_config(server_id)["excluded_dirs"] + excluded_dirs = HelpersManagement.get_backup_config(server_id)["excluded_dirs"] if excluded_dirs is not None and excluded_dirs != "": dir_list = excluded_dirs.split(",") else: diff --git a/app/classes/models/roles.py b/app/classes/models/roles.py index 261f2479..373fa11d 100644 --- a/app/classes/models/roles.py +++ b/app/classes/models/roles.py @@ -29,7 +29,7 @@ class Roles(BaseModel): # ********************************************************************************** # Roles Helpers # ********************************************************************************** -class helper_roles: +class HelperRoles: def __init__(self, database): self.database = database @@ -70,6 +70,6 @@ class helper_roles: @staticmethod def role_id_exists(role_id): - if not helper_roles.get_role(role_id): + if not HelperRoles.get_role(role_id): return False return True diff --git a/app/classes/models/server_permissions.py b/app/classes/models/server_permissions.py index 7ba524b1..b36a275d 100644 --- a/app/classes/models/server_permissions.py +++ b/app/classes/models/server_permissions.py @@ -10,7 +10,7 @@ from peewee import ( from app.classes.models.base_model import BaseModel from app.classes.models.servers import Servers from app.classes.models.roles import Roles -from app.classes.models.users import User_Roles, helper_users, ApiKeys, Users +from app.classes.models.users import UserRoles, HelperUsers, ApiKeys, Users from app.classes.shared.permission_helper import PermissionHelper logger = logging.getLogger(__name__) @@ -18,7 +18,7 @@ logger = logging.getLogger(__name__) # ********************************************************************************** # Role Servers Class # ********************************************************************************** -class Role_Servers(BaseModel): +class RoleServers(BaseModel): role_id = ForeignKeyField(Roles, backref="role_server") server_id = ForeignKeyField(Servers, backref="role_server") permissions = CharField(default="00000000") @@ -31,46 +31,46 @@ class Role_Servers(BaseModel): # ********************************************************************************** # Servers Permissions Class # ********************************************************************************** -class Enum_Permissions_Server(Enum): - Commands = 0 - Terminal = 1 - Logs = 2 - Schedule = 3 - Backup = 4 - Files = 5 - Config = 6 - Players = 7 +class EnumPermissionsServer(Enum): + COMMANDS = 0 + TERMINAL = 1 + LOGS = 2 + SCHEDULE = 3 + BACKUP = 4 + FILES = 5 + CONFIG = 6 + PLAYERS = 7 -class Permissions_Servers: +class PermissionsServers: @staticmethod def get_or_create(role_id, server, permissions_mask): - return Role_Servers.get_or_create( + return RoleServers.get_or_create( role_id=role_id, server_id=server, permissions=permissions_mask ) @staticmethod def get_permissions_list(): permissions_list = [] - for member in Enum_Permissions_Server.__members__.items(): + for member in EnumPermissionsServer.__members__.items(): permissions_list.append(member[1]) return permissions_list @staticmethod def get_permissions(permissions_mask): permissions_list = [] - for member in Enum_Permissions_Server.__members__.items(): - if Permissions_Servers.has_permission(permissions_mask, member[1]): + for member in EnumPermissionsServer.__members__.items(): + if PermissionsServers.has_permission(permissions_mask, member[1]): permissions_list.append(member[1]) return permissions_list @staticmethod - def has_permission(permission_mask, permission_tested: Enum_Permissions_Server): + def has_permission(permission_mask, permission_tested: EnumPermissionsServer): return permission_mask[permission_tested.value] == "1" @staticmethod def set_permission( - permission_mask, permission_tested: Enum_Permissions_Server, value + permission_mask, permission_tested: EnumPermissionsServer, value ): list_perms = list(permission_mask) list_perms[permission_tested.value] = str(value) @@ -78,13 +78,13 @@ class Permissions_Servers: return permission_mask @staticmethod - def get_permission(permission_mask, permission_tested: Enum_Permissions_Server): + def get_permission(permission_mask, permission_tested: EnumPermissionsServer): return permission_mask[permission_tested.value] @staticmethod def get_token_permissions(permissions_mask, api_permissions_mask): permissions_list = [] - for member in Enum_Permissions_Server.__members__.items(): + for member in EnumPermissionsServer.__members__.items(): if PermissionHelper.both_have_perm( permissions_mask, api_permissions_mask, member[1] ): @@ -96,31 +96,31 @@ class Permissions_Servers: # ********************************************************************************** @staticmethod def get_role_servers_from_role_id(roleid): - return Role_Servers.select().where(Role_Servers.role_id == roleid) + return RoleServers.select().where(RoleServers.role_id == roleid) @staticmethod def get_servers_from_role(role_id): return ( - Role_Servers.select() + RoleServers.select() .join(Servers, JOIN.INNER) - .where(Role_Servers.role_id == role_id) + .where(RoleServers.role_id == role_id) ) @staticmethod def get_roles_from_server(server_id): return ( - Role_Servers.select() + RoleServers.select() .join(Roles, JOIN.INNER) - .where(Role_Servers.server_id == server_id) + .where(RoleServers.server_id == server_id) ) @staticmethod def add_role_server(server_id, role_id, rs_permissions="00000000"): - servers = Role_Servers.insert( + servers = RoleServers.insert( { - Role_Servers.server_id: server_id, - Role_Servers.role_id: role_id, - Role_Servers.permissions: rs_permissions, + RoleServers.server_id: server_id, + RoleServers.role_id: role_id, + RoleServers.permissions: rs_permissions, } ).execute() return servers @@ -129,9 +129,9 @@ class Permissions_Servers: def get_permissions_mask(role_id, server_id): permissions_mask = "" role_server = ( - Role_Servers.select() - .where(Role_Servers.role_id == role_id) - .where(Role_Servers.server_id == server_id) + RoleServers.select() + .where(RoleServers.role_id == role_id) + .where(RoleServers.server_id == server_id) .get() ) permissions_mask = role_server.permissions @@ -140,9 +140,7 @@ class Permissions_Servers: @staticmethod def get_server_roles(server_id): role_list = [] - roles = ( - Role_Servers.select().where(Role_Servers.server_id == server_id).execute() - ) + roles = RoleServers.select().where(RoleServers.server_id == server_id).execute() for role in roles: role_list.append(role.role_id) return role_list @@ -150,72 +148,70 @@ class Permissions_Servers: @staticmethod def get_role_permissions_list(role_id): permissions_mask = "00000000" - role_server = Role_Servers.get_or_none(Role_Servers.role_id == role_id) + role_server = RoleServers.get_or_none(RoleServers.role_id == role_id) if role_server is not None: permissions_mask = role_server.permissions - permissions_list = Permissions_Servers.get_permissions(permissions_mask) + permissions_list = PermissionsServers.get_permissions(permissions_mask) return permissions_list @staticmethod def update_role_permission(role_id, server_id, permissions_mask): role_server = ( - Role_Servers.select() - .where(Role_Servers.role_id == role_id) - .where(Role_Servers.server_id == server_id) + RoleServers.select() + .where(RoleServers.role_id == role_id) + .where(RoleServers.server_id == server_id) .get() ) role_server.permissions = permissions_mask - Role_Servers.save(role_server) + RoleServers.save(role_server) @staticmethod def delete_roles_permissions(role_id, removed_servers=None): if removed_servers is None: removed_servers = {} return ( - Role_Servers.delete() - .where(Role_Servers.role_id == role_id) - .where(Role_Servers.server_id.in_(removed_servers)) + RoleServers.delete() + .where(RoleServers.role_id == role_id) + .where(RoleServers.server_id.in_(removed_servers)) .execute() ) @staticmethod def remove_roles_of_server(server_id): - return ( - Role_Servers.delete().where(Role_Servers.server_id == server_id).execute() - ) + return RoleServers.delete().where(RoleServers.server_id == server_id).execute() @staticmethod def get_user_id_permissions_mask(user_id, server_id: str): - user = helper_users.get_user_model(user_id) - return Permissions_Servers.get_user_permissions_mask(user, server_id) + user = HelperUsers.get_user_model(user_id) + return PermissionsServers.get_user_permissions_mask(user, server_id) @staticmethod def get_user_permissions_mask(user: Users, server_id: str): if user.superuser: - permissions_mask = "1" * len(Permissions_Servers.get_permissions_list()) + permissions_mask = "1" * len(PermissionsServers.get_permissions_list()) else: - roles_list = helper_users.get_user_roles_id(user.user_id) + roles_list = HelperUsers.get_user_roles_id(user.user_id) role_server = ( - Role_Servers.select() - .where(Role_Servers.role_id.in_(roles_list)) - .where(Role_Servers.server_id == server_id) + RoleServers.select() + .where(RoleServers.role_id.in_(roles_list)) + .where(RoleServers.server_id == server_id) .execute() ) try: permissions_mask = role_server[0].permissions except IndexError: - permissions_mask = "0" * len(Permissions_Servers.get_permissions_list()) + permissions_mask = "0" * len(PermissionsServers.get_permissions_list()) return permissions_mask @staticmethod def get_server_user_list(server_id): final_users = [] - server_roles = Role_Servers.select().where(Role_Servers.server_id == server_id) + server_roles = RoleServers.select().where(RoleServers.server_id == server_id) super_users = Users.select().where( Users.superuser == True # pylint: disable=singleton-comparison ) for role in server_roles: - users = User_Roles.select().where(User_Roles.role_id == role.role_id) + users = UserRoles.select().where(UserRoles.role_id == role.role_id) for user in users: if user.user_id.user_id not in final_users: final_users.append(user.user_id.user_id) @@ -226,36 +222,36 @@ class Permissions_Servers: @staticmethod def get_user_id_permissions_list(user_id, server_id: str): - user = helper_users.get_user_model(user_id) - return Permissions_Servers.get_user_permissions_list(user, server_id) + user = HelperUsers.get_user_model(user_id) + return PermissionsServers.get_user_permissions_list(user, server_id) @staticmethod def get_user_permissions_list(user: Users, server_id: str): if user.superuser: - permissions_list = Permissions_Servers.get_permissions_list() + permissions_list = PermissionsServers.get_permissions_list() else: - permissions_mask = Permissions_Servers.get_user_permissions_mask( + permissions_mask = PermissionsServers.get_user_permissions_mask( user, server_id ) - permissions_list = Permissions_Servers.get_permissions(permissions_mask) + permissions_list = PermissionsServers.get_permissions(permissions_mask) return permissions_list @staticmethod def get_api_key_id_permissions_list(key_id, server_id: str): key = ApiKeys.get(ApiKeys.token_id == key_id) - return Permissions_Servers.get_api_key_permissions_list(key, server_id) + return PermissionsServers.get_api_key_permissions_list(key, server_id) @staticmethod def get_api_key_permissions_list(key: ApiKeys, server_id: str): - user = helper_users.get_user(key.user_id) + user = HelperUsers.get_user(key.user_id) if user["superuser"] and key.superuser: - return Permissions_Servers.get_permissions_list() + return PermissionsServers.get_permissions_list() else: - roles_list = helper_users.get_user_roles_id(user["user_id"]) + roles_list = HelperUsers.get_user_roles_id(user["user_id"]) role_server = ( - Role_Servers.select() - .where(Role_Servers.role_id.in_(roles_list)) - .where(Role_Servers.server_id == server_id) + RoleServers.select() + .where(RoleServers.role_id.in_(roles_list)) + .where(RoleServers.server_id == server_id) .execute() ) try: @@ -269,5 +265,5 @@ class Permissions_Servers: permissions_mask = PermissionHelper.combine_masks( user_permissions_mask, key_permissions_mask ) - permissions_list = Permissions_Servers.get_permissions(permissions_mask) + permissions_list = PermissionsServers.get_permissions(permissions_mask) return permissions_list diff --git a/app/classes/models/servers.py b/app/classes/models/servers.py index c93ff490..aa6744c0 100644 --- a/app/classes/models/servers.py +++ b/app/classes/models/servers.py @@ -10,7 +10,7 @@ from peewee import ( FloatField, ) -from app.classes.shared.main_models import db_shortcuts +from app.classes.shared.main_models import DatabaseShortcuts from app.classes.models.base_model import BaseModel logger = logging.getLogger(__name__) @@ -45,7 +45,7 @@ class Servers(BaseModel): # ********************************************************************************** # Servers Stats Class # ********************************************************************************** -class Server_Stats(BaseModel): +class ServerStats(BaseModel): stats_id = AutoField() created = DateTimeField(default=datetime.datetime.now) server_id = ForeignKeyField(Servers, backref="server", index=True) @@ -76,7 +76,7 @@ class Server_Stats(BaseModel): # ********************************************************************************** # Servers Class # ********************************************************************************** -class helper_servers: +class HelperServers: def __init__(self, database): self.database = database @@ -135,7 +135,7 @@ class helper_servers: def get_server_data_by_id(server_id): query = Servers.select().where(Servers.server_id == server_id).limit(1) try: - return db_shortcuts.return_rows(query)[0] + return DatabaseShortcuts.return_rows(query)[0] except IndexError: return {} @@ -145,24 +145,24 @@ class helper_servers: @staticmethod def get_all_defined_servers(): query = Servers.select() - return db_shortcuts.return_rows(query) + return DatabaseShortcuts.return_rows(query) @staticmethod def get_all_servers_stats(): - servers = helper_servers.get_all_defined_servers() + servers = HelperServers.get_all_defined_servers() server_data = [] try: for s in servers: latest = ( - Server_Stats.select() - .where(Server_Stats.server_id == s.get("server_id")) - .order_by(Server_Stats.created.desc()) + ServerStats.select() + .where(ServerStats.server_id == s.get("server_id")) + .order_by(ServerStats.created.desc()) .limit(1) ) server_data.append( { "server_data": s, - "stats": db_shortcuts.return_rows(latest)[0], + "stats": DatabaseShortcuts.return_rows(latest)[0], "user_command_permission": True, } ) @@ -174,7 +174,7 @@ class helper_servers: @staticmethod def get_server_friendly_name(server_id): - server_data = helper_servers.get_server_data_by_id(server_id) + server_data = HelperServers.get_server_data_by_id(server_id) friendly_name = ( f"{server_data.get('server_name', None)} " f"with ID: {server_data.get('server_id', 0)}" @@ -187,62 +187,62 @@ class helper_servers: @staticmethod def get_latest_server_stats(server_id): return ( - Server_Stats.select() - .where(Server_Stats.server_id == server_id) - .order_by(Server_Stats.created.desc()) + ServerStats.select() + .where(ServerStats.server_id == server_id) + .order_by(ServerStats.created.desc()) .limit(1) ) @staticmethod def get_server_stats_by_id(server_id): stats = ( - Server_Stats.select() - .where(Server_Stats.server_id == server_id) - .order_by(Server_Stats.created.desc()) + ServerStats.select() + .where(ServerStats.server_id == server_id) + .order_by(ServerStats.created.desc()) .limit(1) ) - return db_shortcuts.return_rows(stats)[0] + return DatabaseShortcuts.return_rows(stats)[0] @staticmethod def server_id_exists(server_id): - if not helper_servers.get_server_data_by_id(server_id): + if not HelperServers.get_server_data_by_id(server_id): return False return True @staticmethod def sever_crashed(server_id): - Server_Stats.update(crashed=True).where( - Server_Stats.server_id == server_id + ServerStats.update(crashed=True).where( + ServerStats.server_id == server_id ).execute() @staticmethod def set_download(server_id): - Server_Stats.update(downloading=True).where( - Server_Stats.server_id == server_id + ServerStats.update(downloading=True).where( + ServerStats.server_id == server_id ).execute() @staticmethod def finish_download(server_id): - Server_Stats.update(downloading=False).where( - Server_Stats.server_id == server_id + ServerStats.update(downloading=False).where( + ServerStats.server_id == server_id ).execute() @staticmethod def get_download_status(server_id): download_status = ( - Server_Stats.select().where(Server_Stats.server_id == server_id).get() + ServerStats.select().where(ServerStats.server_id == server_id).get() ) return download_status.downloading @staticmethod def server_crash_reset(server_id): - Server_Stats.update(crashed=False).where( - Server_Stats.server_id == server_id + ServerStats.update(crashed=False).where( + ServerStats.server_id == server_id ).execute() @staticmethod def is_crashed(server_id): - svr = Server_Stats.select().where(Server_Stats.server_id == server_id).get() + svr = ServerStats.select().where(ServerStats.server_id == server_id).get() if svr.crashed is True: return True else: @@ -252,17 +252,17 @@ class helper_servers: def set_update(server_id, value): try: # Checks if server even exists - Server_Stats.select().where(Server_Stats.server_id == server_id) + ServerStats.select().where(ServerStats.server_id == server_id) except Exception as ex: logger.error(f"Database entry not found! {ex}") - Server_Stats.update(updating=value).where( - Server_Stats.server_id == server_id + ServerStats.update(updating=value).where( + ServerStats.server_id == server_id ).execute() @staticmethod def get_update_status(server_id): update_status = ( - Server_Stats.select().where(Server_Stats.server_id == server_id).get() + ServerStats.select().where(ServerStats.server_id == server_id).get() ) return update_status.updating @@ -271,34 +271,32 @@ class helper_servers: # Sets first run to false try: # Checks if server even exists - Server_Stats.select().where(Server_Stats.server_id == server_id) + ServerStats.select().where(ServerStats.server_id == server_id) except Exception as ex: logger.error(f"Database entry not found! {ex}") return - Server_Stats.update(first_run=False).where( - Server_Stats.server_id == server_id + ServerStats.update(first_run=False).where( + ServerStats.server_id == server_id ).execute() @staticmethod def get_first_run(server_id): - first_run = ( - Server_Stats.select().where(Server_Stats.server_id == server_id).get() - ) + first_run = ServerStats.select().where(ServerStats.server_id == server_id).get() return first_run.first_run @staticmethod - def get_TTL_without_player(server_id): + def get_ttl_without_player(server_id): last_stat = ( - Server_Stats.select() - .where(Server_Stats.server_id == server_id) - .order_by(Server_Stats.created.desc()) + ServerStats.select() + .where(ServerStats.server_id == server_id) + .order_by(ServerStats.created.desc()) .first() ) last_stat_with_player = ( - Server_Stats.select() - .where(Server_Stats.server_id == server_id) - .where(Server_Stats.online > 0) - .order_by(Server_Stats.created.desc()) + ServerStats.select() + .where(ServerStats.server_id == server_id) + .where(ServerStats.online > 0) + .order_by(ServerStats.created.desc()) .first() ) return last_stat.created - last_stat_with_player.created @@ -306,7 +304,7 @@ class helper_servers: @staticmethod def can_stop_no_players(server_id, time_limit): can = False - ttl_no_players = helper_servers.get_TTL_without_player(server_id) + ttl_no_players = HelperServers.get_ttl_without_player(server_id) if (time_limit == -1) or (ttl_no_players > time_limit): can = True return can @@ -315,16 +313,16 @@ class helper_servers: def set_waiting_start(server_id, value): try: # Checks if server even exists - Server_Stats.select().where(Server_Stats.server_id == server_id) + ServerStats.select().where(ServerStats.server_id == server_id) except Exception as ex: logger.error(f"Database entry not found! {ex}") - Server_Stats.update(waiting_start=value).where( - Server_Stats.server_id == server_id + ServerStats.update(waiting_start=value).where( + ServerStats.server_id == server_id ).execute() @staticmethod def get_waiting_start(server_id): waiting_start = ( - Server_Stats.select().where(Server_Stats.server_id == server_id).get() + ServerStats.select().where(ServerStats.server_id == server_id).get() ) return waiting_start.waiting_start diff --git a/app/classes/models/users.py b/app/classes/models/users.py index ee44114d..ddfdbd8f 100644 --- a/app/classes/models/users.py +++ b/app/classes/models/users.py @@ -16,7 +16,7 @@ from playhouse.shortcuts import model_to_dict from app.classes.shared.helpers import Helpers from app.classes.models.base_model import BaseModel -from app.classes.models.roles import Roles, helper_roles +from app.classes.models.roles import Roles, HelperRoles logger = logging.getLogger(__name__) @@ -64,7 +64,7 @@ class ApiKeys(BaseModel): # ********************************************************************************** # User Roles Class # ********************************************************************************** -class User_Roles(BaseModel): +class UserRoles(BaseModel): user_id = ForeignKeyField(Users, backref="user_role") role_id = ForeignKeyField(Roles, backref="user_role") @@ -76,7 +76,7 @@ class User_Roles(BaseModel): # ********************************************************************************** # Users Helpers # ********************************************************************************** -class helper_users: +class HelperUsers: def __init__(self, database, helper): self.database = database self.helper = helper @@ -128,7 +128,7 @@ class helper_users: if user: # I know it should apply it without setting it but I'm just making sure - user = helper_users.add_user_roles(user) + user = HelperUsers.add_user_roles(user) return user else: # logger.debug("user: ({}) {}".format(user_id, {})) @@ -146,7 +146,7 @@ class helper_users: @staticmethod def get_user_model(user_id: str) -> Users: user = Users.get(Users.user_id == user_id) - user = helper_users.add_user_roles(user) + user = HelperUsers.add_user_roles(user) return user def add_user( @@ -223,7 +223,7 @@ class helper_users: def remove_user(self, user_id): with self.database.atomic(): - User_Roles.delete().where(User_Roles.user_id == user_id).execute() + UserRoles.delete().where(UserRoles.user_id == user_id).execute() user = Users.get(Users.user_id == user_id) return user.delete_instance() @@ -249,7 +249,7 @@ class helper_users: @staticmethod def user_id_exists(user_id): - if not helper_users.get_user(user_id): + if not HelperUsers.get_user(user_id): return False return True @@ -259,28 +259,28 @@ class helper_users: @staticmethod def get_or_create(user_id, role_id): - return User_Roles.get_or_create(user_id=user_id, role_id=role_id) + return UserRoles.get_or_create(user_id=user_id, role_id=role_id) @staticmethod def get_user_roles_id(user_id): roles_list = [] - roles = User_Roles.select().where(User_Roles.user_id == user_id) + roles = UserRoles.select().where(UserRoles.user_id == user_id) for r in roles: - roles_list.append(helper_roles.get_role(r.role_id)["role_id"]) + roles_list.append(HelperRoles.get_role(r.role_id)["role_id"]) return roles_list @staticmethod def get_user_roles_names(user_id): roles_list = [] - roles = User_Roles.select().where(User_Roles.user_id == user_id) + roles = UserRoles.select().where(UserRoles.user_id == user_id) for r in roles: - roles_list.append(helper_roles.get_role(r.role_id)["role_name"]) + roles_list.append(HelperRoles.get_role(r.role_id)["role_name"]) return roles_list @staticmethod def add_role_to_user(user_id, role_id): - User_Roles.insert( - {User_Roles.user_id: user_id, User_Roles.role_id: role_id} + UserRoles.insert( + {UserRoles.user_id: user_id, UserRoles.role_id: role_id} ).execute() @staticmethod @@ -294,9 +294,9 @@ class helper_users: # it had those TODOs & comments made by mac - Lukas roles_query = ( - User_Roles.select() + UserRoles.select() .join(Roles, JOIN.INNER) - .where(User_Roles.user_id == user_id) + .where(UserRoles.user_id == user_id) ) # TODO: this query needs to be narrower roles = set() @@ -313,21 +313,21 @@ class helper_users: @staticmethod def user_role_query(user_id): - user_query = User_Roles.select().where(User_Roles.user_id == user_id) + user_query = UserRoles.select().where(UserRoles.user_id == user_id) query = Roles.select().where(Roles.role_id == -1) - for u in user_query: - query = query + Roles.select().where(Roles.role_id == u.role_id) + for user in user_query: + query = query + Roles.select().where(Roles.role_id == user.role_id) return query @staticmethod def delete_user_roles(user_id, removed_roles): - User_Roles.delete().where(User_Roles.user_id == user_id).where( - User_Roles.role_id.in_(removed_roles) + UserRoles.delete().where(UserRoles.user_id == user_id).where( + UserRoles.role_id.in_(removed_roles) ).execute() @staticmethod def remove_roles_from_role_id(role_id): - User_Roles.delete().where(User_Roles.role_id == role_id).execute() + UserRoles.delete().where(UserRoles.role_id == role_id).execute() # ********************************************************************************** # ApiKeys Methods diff --git a/app/classes/shared/authentication.py b/app/classes/shared/authentication.py index bab36c28..fbe2fb58 100644 --- a/app/classes/shared/authentication.py +++ b/app/classes/shared/authentication.py @@ -4,7 +4,7 @@ from typing import Optional, Dict, Any, Tuple import jwt from jwt import PyJWTError -from app.classes.models.users import helper_users, ApiKeys +from app.classes.models.users import HelperUsers, ApiKeys logger = logging.getLogger(__name__) @@ -52,11 +52,11 @@ class Authentication: key: Optional[ApiKeys] = None if "token_id" in data: key_id = data["token_id"] - key = helper_users.get_user_api_key(key_id) + key = HelperUsers.get_user_api_key(key_id) if key is None: return None user_id: str = data["user_id"] - user = helper_users.get_user(user_id) + user = HelperUsers.get_user(user_id) # TODO: Have a cache or something so we don't constantly # have to query the database if int(user.get("valid_tokens_from").timestamp()) < iat: diff --git a/app/classes/shared/command.py b/app/classes/shared/command.py index 961c6d84..f8fa8b48 100644 --- a/app/classes/shared/command.py +++ b/app/classes/shared/command.py @@ -5,7 +5,7 @@ import threading import logging from app.classes.shared.console import Console -from app.classes.shared.import3 import import3 +from app.classes.shared.import3 import Import3 logger = logging.getLogger(__name__) @@ -61,7 +61,7 @@ class MainPrompt(cmd.Cmd): print(f"Name: {thread.name} Identifier: {thread.ident}") def do_import3(self, _line): - import3.start_import() + Import3.start_import() def universal_exit(self): logger.info("Stopping all server daemons / threads") diff --git a/app/classes/shared/console.py b/app/classes/shared/console.py index d885298e..4c330cf3 100644 --- a/app/classes/shared/console.py +++ b/app/classes/shared/console.py @@ -54,30 +54,30 @@ class Console: @staticmethod def debug(message): - dt = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") - Console.magenta(f"[+] Crafty: {dt} - DEBUG:\t{message}") + date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") + Console.magenta(f"[+] Crafty: {date_time} - DEBUG:\t{message}") @staticmethod def info(message): - dt = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") - Console.white(f"[+] Crafty: {dt} - INFO:\t{message}") + date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") + Console.white(f"[+] Crafty: {date_time} - INFO:\t{message}") @staticmethod def warning(message): - dt = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") - Console.cyan(f"[+] Crafty: {dt} - WARNING:\t{message}") + date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") + Console.cyan(f"[+] Crafty: {date_time} - WARNING:\t{message}") @staticmethod def error(message): - dt = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") - Console.yellow(f"[+] Crafty: {dt} - ERROR:\t{message}") + date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") + Console.yellow(f"[+] Crafty: {date_time} - ERROR:\t{message}") @staticmethod def critical(message): - dt = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") - Console.red(f"[+] Crafty: {dt} - CRITICAL:\t{message}") + date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") + Console.red(f"[+] Crafty: {date_time} - CRITICAL:\t{message}") @staticmethod def help(message): - dt = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") - Console.green(f"[+] Crafty: {dt} - HELP:\t{message}") + date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") + Console.green(f"[+] Crafty: {date_time} - HELP:\t{message}") diff --git a/app/classes/shared/file_helpers.py b/app/classes/shared/file_helpers.py index b6f4d223..dad6ddef 100644 --- a/app/classes/shared/file_helpers.py +++ b/app/classes/shared/file_helpers.py @@ -60,19 +60,19 @@ class FileHelpers: def make_archive(path_to_destination, path_to_zip): # create a ZipFile object path_to_destination += ".zip" - with ZipFile(path_to_destination, "w") as z: + with ZipFile(path_to_destination, "w") as zip_file: for root, _dirs, files in os.walk(path_to_zip, topdown=True): ziproot = path_to_zip for file in files: try: logger.info(f"backing up: {os.path.join(root, file)}") if os.name == "nt": - z.write( + zip_file.write( os.path.join(root, file), os.path.join(root.replace(ziproot, ""), file), ) else: - z.write( + zip_file.write( os.path.join(root, file), os.path.join(root.replace(ziproot, "/"), file), ) @@ -89,19 +89,19 @@ class FileHelpers: def make_compressed_archive(path_to_destination, path_to_zip): # create a ZipFile object path_to_destination += ".zip" - with ZipFile(path_to_destination, "w", ZIP_DEFLATED) as z: + with ZipFile(path_to_destination, "w", ZIP_DEFLATED) as zip_file: for root, _dirs, files in os.walk(path_to_zip, topdown=True): ziproot = path_to_zip for file in files: try: logger.info(f"backing up: {os.path.join(root, file)}") if os.name == "nt": - z.write( + zip_file.write( os.path.join(root, file), os.path.join(root.replace(ziproot, ""), file), ) else: - z.write( + zip_file.write( os.path.join(root, file), os.path.join(root.replace(ziproot, "/"), file), ) diff --git a/app/classes/shared/helpers.py b/app/classes/shared/helpers.py index 80dcec59..caf6438b 100644 --- a/app/classes/shared/helpers.py +++ b/app/classes/shared/helpers.py @@ -146,47 +146,51 @@ class Helpers: def cmdparse(cmd_in): # Parse a string into arguments cmd_out = [] # "argv" output array - ci = -1 # command index - pointer to the argument we're building in cmd_out - np = True # whether we're creating a new argument/parameter + cmd_index = ( + -1 + ) # command index - pointer to the argument we're building in cmd_out + new_param = True # whether we're creating a new argument/parameter esc = False # whether an escape character was encountered - stch = None # if we're dealing with a quote, save the quote type here. + quote_char = None # if we're dealing with a quote, save the quote type here. # Nested quotes to be dealt with by the command - for c in cmd_in: # for character in string - if np: # if set, begin a new argument and increment the command index. + for char in cmd_in: # for character in string + if ( + new_param + ): # if set, begin a new argument and increment the command index. # Continue the loop. - if c == " ": + if char == " ": continue else: - ci += 1 + cmd_index += 1 cmd_out.append("") - np = False + new_param = False if esc: # if we encountered an escape character on the last loop, # append this char regardless of what it is - if c not in Helpers.allowed_quotes: - cmd_out[ci] += "\\" - cmd_out[ci] += c + if char not in Helpers.allowed_quotes: + cmd_out[cmd_index] += "\\" + cmd_out[cmd_index] += char esc = False else: - if c == "\\": # if the current character is an escape character, + if char == "\\": # if the current character is an escape character, # set the esc flag and continue to next loop esc = True elif ( - c == " " and stch is None + char == " " and quote_char is None ): # if we encounter a space and are not dealing with a quote, # set the new argument flag and continue to next loop - np = True + new_param = True elif ( - c == stch + char == quote_char ): # if we encounter the character that matches our start quote, # end the quote and continue to next loop - stch = None - elif stch is None and ( - c in Helpers.allowed_quotes + quote_char = None + elif quote_char is None and ( + char in Helpers.allowed_quotes ): # if we're not in the middle of a quote and we get a quotable # character, start a quote and proceed to the next loop - stch = c + quote_char = char else: # else, just store the character in the current arg - cmd_out[ci] += c + cmd_out[cmd_index] += char return cmd_out def get_setting(self, key, default_return=False): @@ -244,12 +248,12 @@ class Helpers: try: # doesn't even have to be reachable s.connect(("10.255.255.255", 1)) - IP = s.getsockname()[0] + ip = s.getsockname()[0] except Exception: - IP = "127.0.0.1" + ip = "127.0.0.1" finally: s.close() - return IP + return ip def get_version(self): version_data = {} @@ -266,16 +270,16 @@ class Helpers: @staticmethod def get_announcements(): - r = requests.get("https://craftycontrol.com/notify.json", timeout=2) + response = requests.get("https://craftycontrol.com/notify.json", timeout=2) data = ( '[{"id":"1","date":"Unknown",' '"title":"Error getting Announcements",' '"desc":"Error getting Announcements","link":""}]' ) - if r.status_code in [200, 201]: + if response.status_code in [200, 201]: try: - data = json.loads(r.content) + data = json.loads(response.content) except Exception as e: logger.error(f"Failed to load json content with error: {e}") @@ -344,8 +348,8 @@ class Helpers: base = pathlib.Path(base_path).resolve() file = pathlib.Path(filename) fileabs = base.joinpath(file).resolve() - cp = pathlib.Path(os.path.commonpath([base, fileabs])) - if base == cp: + common_path = pathlib.Path(os.path.commonpath([base, fileabs])) + if base == common_path: return fileabs else: raise ValueError("Path traversal detected") @@ -402,7 +406,7 @@ class Helpers: return False @staticmethod - def checkRoot(): + def check_root(): if Helpers.is_os_windows(): if ctypes.windll.shell32.IsUserAnAdmin() == 1: return True @@ -415,7 +419,7 @@ class Helpers: return False @staticmethod - def unzipFile(zip_path): + def unzip_file(zip_path): new_dir_list = zip_path.split("/") new_dir = "" for i in range(len(new_dir_list) - 1): @@ -426,17 +430,17 @@ class Helpers: if Helpers.check_file_perms(zip_path) and os.path.isfile(zip_path): Helpers.ensure_dir_exists(new_dir) - tempDir = tempfile.mkdtemp() + temp_dir = tempfile.mkdtemp() try: with zipfile.ZipFile(zip_path, "r") as zip_ref: - zip_ref.extractall(tempDir) + zip_ref.extractall(temp_dir) for i in enumerate(zip_ref.filelist): if len(zip_ref.filelist) > 1 or not zip_ref.filelist[ i ].filename.endswith("/"): break - full_root_path = tempDir + full_root_path = temp_dir for item in os.listdir(full_root_path): try: @@ -497,9 +501,9 @@ class Helpers: source_size = 0 files_count = 0 for path, _dirs, files in os.walk(source_path): - for f in files: - fp = os.path.join(path, f) - source_size += os.stat(fp).st_size + for file in files: + full_path = os.path.join(path, file) + source_size += os.stat(full_path).st_size files_count += 1 dest_size = os.path.getsize(str(dest_path)) percent = round((dest_size / source_size) * 100, 1) @@ -719,11 +723,13 @@ class Helpers: "DNS:127.0.0.1", ] ).encode() - subjectAltNames_Ext = crypto.X509Extension(b"subjectAltName", False, alt_names) - basicConstraints_Ext = crypto.X509Extension( + subject_alt_names_ext = crypto.X509Extension( + b"subjectAltName", False, alt_names + ) + basic_constraints_ext = crypto.X509Extension( b"basicConstraints", True, b"CA:false" ) - cert.add_extensions([subjectAltNames_Ext, basicConstraints_Ext]) + cert.add_extensions([subject_alt_names_ext, basic_constraints_ext]) cert.set_serial_number(random.randint(1, 255)) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(365 * 24 * 60 * 60) @@ -903,15 +909,15 @@ class Helpers:
  • """ return output - def unzipServer(self, zip_path, user_id): + def unzip_server(self, zip_path, user_id): if Helpers.check_file_perms(zip_path): - tempDir = tempfile.mkdtemp() + temp_dir = tempfile.mkdtemp() with zipfile.ZipFile(zip_path, "r") as zip_ref: # extracts archive to temp directory - zip_ref.extractall(tempDir) + zip_ref.extractall(temp_dir) if user_id: self.websocket_helper.broadcast_user( - user_id, "send_temp_path", {"path": tempDir} + user_id, "send_temp_path", {"path": temp_dir} ) def backup_select(self, path, user_id): @@ -924,11 +930,11 @@ class Helpers: def unzip_backup_archive(backup_path, zip_name): zip_path = os.path.join(backup_path, zip_name) if Helpers.check_file_perms(zip_path): - tempDir = tempfile.mkdtemp() + temp_dir = tempfile.mkdtemp() with zipfile.ZipFile(zip_path, "r") as zip_ref: # extracts archive to temp directory - zip_ref.extractall(tempDir) - return tempDir + zip_ref.extractall(temp_dir) + return temp_dir else: return False @@ -948,10 +954,6 @@ class Helpers: [parent_path, child_path] ) - @staticmethod - def in_path_old(x, y): - return os.path.abspath(y).__contains__(os.path.abspath(x)) - @staticmethod def copy_files(source, dest): if os.path.isfile(source): @@ -963,16 +965,16 @@ class Helpers: @staticmethod def download_file(executable_url, jar_path): try: - r = requests.get(executable_url, timeout=5) + response = requests.get(executable_url, timeout=5) except Exception as ex: logger.error("Could not download executable: %s", ex) return False - if r.status_code != 200: + if response.status_code != 200: logger.error("Unable to download file from %s", executable_url) return False try: - open(jar_path, "wb").write(r.content) + open(jar_path, "wb").write(response.content) except Exception as e: logger.error("Unable to finish executable download. Error: %s", e) return False @@ -985,7 +987,7 @@ class Helpers: return text @staticmethod - def getLangPage(text): + def get_lang_page(text): lang = text.split("_")[0] region = text.split("_")[1] if region == "EN": diff --git a/app/classes/shared/import3.py b/app/classes/shared/import3.py index 6d36371d..d3ef7a91 100644 --- a/app/classes/shared/import3.py +++ b/app/classes/shared/import3.py @@ -2,13 +2,13 @@ import json import os import logging -from app.classes.controllers.users_controller import helper_users +from app.classes.controllers.users_controller import HelperUsers from app.classes.shared.console import Console logger = logging.getLogger(__name__) -class import3: +class Import3: def __init__(self, helper, controller): self.helper = helper self.controller = controller @@ -38,7 +38,7 @@ class import3: # If there is only one user to import json needs to call the data differently if isinstance(json_data, list): for user in json_data: - helper_users.add_rawpass_user(user["username"], user["password"]) + HelperUsers.add_rawpass_user(user["username"], user["password"]) Console.info(f"Imported user {user['username']} from Crafty 3") logger.info(f"Imported user {user['username']} from Crafty 3") else: diff --git a/app/classes/shared/installer.py b/app/classes/shared/installer.py index 801c4ae0..d82d2399 100644 --- a/app/classes/shared/installer.py +++ b/app/classes/shared/installer.py @@ -2,7 +2,7 @@ import sys import subprocess -class install: +class Install: @staticmethod def is_venv(): return hasattr(sys, "real_prefix") or ( @@ -24,4 +24,4 @@ class install: sys.exit(0) -installer = install() +installer = Install() diff --git a/app/classes/shared/main_controller.py b/app/classes/shared/main_controller.py index 2fccef9c..d59984e3 100644 --- a/app/classes/shared/main_controller.py +++ b/app/classes/shared/main_controller.py @@ -12,17 +12,17 @@ from peewee import DoesNotExist from tzlocal import get_localzone from apscheduler.schedulers.background import BackgroundScheduler -from app.classes.controllers.crafty_perms_controller import Crafty_Perms_Controller -from app.classes.controllers.management_controller import Management_Controller -from app.classes.controllers.users_controller import Users_Controller -from app.classes.controllers.roles_controller import Roles_Controller -from app.classes.controllers.server_perms_controller import Server_Perms_Controller -from app.classes.controllers.servers_controller import Servers_Controller -from app.classes.models.server_permissions import Enum_Permissions_Server -from app.classes.models.users import helper_users -from app.classes.models.roles import helper_roles -from app.classes.models.management import helpers_management -from app.classes.models.servers import helper_servers +from app.classes.controllers.crafty_perms_controller import CraftyPermsController +from app.classes.controllers.management_controller import ManagementController +from app.classes.controllers.users_controller import UsersController +from app.classes.controllers.roles_controller import RolesController +from app.classes.controllers.server_perms_controller import ServerPermsController +from app.classes.controllers.servers_controller import ServersController +from app.classes.models.server_permissions import EnumPermissionsServer +from app.classes.models.users import HelperUsers +from app.classes.models.roles import HelperRoles +from app.classes.models.management import HelpersManagement +from app.classes.models.servers import HelperServers from app.classes.shared.authentication import Authentication from app.classes.shared.console import Console from app.classes.shared.helpers import Helpers @@ -39,19 +39,19 @@ class Controller: def __init__(self, database, helper): self.helper = helper self.server_jars = ServerJars(helper) - self.users_helper = helper_users(database, self.helper) - self.roles_helper = helper_roles(database) - self.servers_helper = helper_servers(database) - self.management_helper = helpers_management(database, self.helper) + self.users_helper = HelperUsers(database, self.helper) + self.roles_helper = HelperRoles(database) + self.servers_helper = HelperServers(database) + self.management_helper = HelpersManagement(database, self.helper) self.authentication = Authentication(self.helper) self.servers_list = [] self.stats = Stats(self.helper, self) - self.crafty_perms = Crafty_Perms_Controller() - self.management = Management_Controller(self.management_helper) - self.roles = Roles_Controller(self.users_helper, self.roles_helper) - self.server_perms = Server_Perms_Controller() - self.servers = Servers_Controller(self.servers_helper) - self.users = Users_Controller( + self.crafty_perms = CraftyPermsController() + self.management = ManagementController(self.management_helper) + self.roles = RolesController(self.users_helper, self.roles_helper) + self.server_perms = ServerPermsController() + self.servers = ServersController(self.servers_helper) + self.users = UsersController( self.helper, self.users_helper, self.authentication ) tz = get_localzone() @@ -62,8 +62,8 @@ class Controller: logger.info(f"Checking to see if we already registered {server_id_to_check}") - for s in self.servers_list: - known_server = s.get("server_id") + for server in self.servers_list: + known_server = server.get("server_id") if known_server is None: return False @@ -80,8 +80,8 @@ class Controller: servers = self.servers.get_all_defined_servers() - for s in servers: - server_id = s.get("server_id") + for server in servers: + server_id = server.get("server_id") # if we have already initialized this server, let's skip it. if self.check_server_loaded(server_id): @@ -89,21 +89,23 @@ class Controller: # if this server path no longer exists - let's warn and bomb out if not Helpers.check_path_exists( - Helpers.get_os_understandable_path(s["path"]) + Helpers.get_os_understandable_path(server["path"]) ): logger.warning( - f"Unable to find server {s['server_name']} at path {s['path']}. " + f"Unable to find server " + f"{server['server_name']} at path {server['path']}. " f"Skipping this server" ) Console.warning( - f"Unable to find server {s['server_name']} at path {s['path']}. " + f"Unable to find server " + f"{server['server_name']} at path {server['path']}. " f"Skipping this server" ) continue settings_file = os.path.join( - Helpers.get_os_understandable_path(s["path"]), "server.properties" + Helpers.get_os_understandable_path(server["path"]), "server.properties" ) # if the properties file isn't there, let's warn @@ -115,28 +117,28 @@ class Controller: settings = ServerProps(settings_file) temp_server_dict = { - "server_id": s.get("server_id"), - "server_data_obj": s, + "server_id": server.get("server_id"), + "server_data_obj": server, "server_obj": Server(self.helper, self.management_helper, self.stats), "server_settings": settings.props, } # setup the server, do the auto start and all that jazz - temp_server_dict["server_obj"].do_server_setup(s) + temp_server_dict["server_obj"].do_server_setup(server) # add this temp object to the list of init servers self.servers_list.append(temp_server_dict) - if s["auto_start"]: - self.servers.set_waiting_start(s["server_id"], True) + if server["auto_start"]: + self.servers.set_waiting_start(server["server_id"], True) - self.refresh_server_settings(s["server_id"]) + self.refresh_server_settings(server["server_id"]) Console.info( - f"Loaded Server: ID {s['server_id']}" - + f" | Name: {s['server_name']}" - + f" | Autostart: {s['auto_start']}" - + f" | Delay: {s['auto_start_delay']} " + f"Loaded Server: ID {server['server_id']}" + f" | Name: {server['server_name']}" + f" | Autostart: {server['auto_start']}" + f" | Delay: {server['auto_start_delay']}" ) def refresh_server_settings(self, server_id: int): @@ -145,7 +147,7 @@ class Controller: @staticmethod def check_system_user(): - if helper_users.get_user_id_by_name("system") is not None: + if HelperUsers.get_user_id_by_name("system") is not None: return True else: return False @@ -162,11 +164,11 @@ class Controller: self.helper.websocket_helper.broadcast_user( exec_user["user_id"], "notification", "Preparing your support logs" ) - tempDir = tempfile.mkdtemp() - tempZipStorage = tempfile.mkdtemp() - full_temp = os.path.join(tempDir, "support_logs") + temp_dir = tempfile.mkdtemp() + temp_zip_storage = tempfile.mkdtemp() + full_temp = os.path.join(temp_dir, "support_logs") os.mkdir(full_temp) - tempZipStorage = os.path.join(tempZipStorage, "support_logs") + temp_zip_storage = os.path.join(temp_zip_storage, "support_logs") crafty_path = os.path.join(full_temp, "crafty") os.mkdir(crafty_path) server_path = os.path.join(full_temp, "server") @@ -180,7 +182,7 @@ class Controller: auth_servers = [] for server in user_servers: if ( - Enum_Permissions_Server.Logs + EnumPermissionsServer.LOGS in self.server_perms.get_user_id_permissions_list( exec_user["user_id"], server["server_id"] ) @@ -211,30 +213,30 @@ class Controller: "interval", seconds=1, id="logs_" + str(exec_user["user_id"]), - args=[full_temp, tempZipStorage + ".zip", exec_user], + args=[full_temp, temp_zip_storage + ".zip", exec_user], ) - FileHelpers.make_archive(tempZipStorage, tempDir) + FileHelpers.make_archive(temp_zip_storage, temp_dir) if len(self.helper.websocket_helper.clients) > 0: self.helper.websocket_helper.broadcast_user( exec_user["user_id"], "support_status_update", - Helpers.calc_percent(full_temp, tempZipStorage + ".zip"), + Helpers.calc_percent(full_temp, temp_zip_storage + ".zip"), ) - tempZipStorage += ".zip" + temp_zip_storage += ".zip" self.helper.websocket_helper.broadcast_user( exec_user["user_id"], "send_logs_bootbox", {} ) - self.users.set_support_path(exec_user["user_id"], tempZipStorage) + self.users.set_support_path(exec_user["user_id"], temp_zip_storage) self.users.stop_prepare(exec_user["user_id"]) self.support_scheduler.remove_job("logs_" + str(exec_user["user_id"])) @staticmethod def add_system_user(): - helper_users.add_user( + HelperUsers.add_user( "system", Helpers.random_string_generator(64), "default@example.com", @@ -243,9 +245,9 @@ class Controller: ) def get_server_settings(self, server_id): - for s in self.servers_list: - if int(s["server_id"]) == int(server_id): - return s["server_settings"] + for server in self.servers_list: + if int(server["server_id"]) == int(server_id): + return server["server_settings"] logger.warning(f"Unable to find server object for server id {server_id}") return False @@ -276,34 +278,34 @@ class Controller: return {"percent": 0, "total_files": 0} def get_server_obj(self, server_id: Union[str, int]) -> Union[bool, Server]: - for s in self.servers_list: - if str(s["server_id"]) == str(server_id): - return s["server_obj"] + for server in self.servers_list: + if str(server["server_id"]) == str(server_id): + return server["server_obj"] logger.warning(f"Unable to find server object for server id {server_id}") return False # TODO: Change to None def get_server_data(self, server_id: str): - for s in self.servers_list: - if str(s["server_id"]) == str(server_id): - return s["server_data_obj"] + for server in self.servers_list: + if str(server["server_id"]) == str(server_id): + return server["server_data_obj"] logger.warning(f"Unable to find server object for server id {server_id}") return False @staticmethod def list_defined_servers(): - servers = helper_servers.get_all_defined_servers() + servers = HelperServers.get_all_defined_servers() return servers def list_running_servers(self): running_servers = [] # for each server - for s in self.servers_list: + for servers in self.servers_list: # is the server running? - srv_obj = s["server_obj"] + srv_obj = servers["server_obj"] running = srv_obj.check_running() # if so, let's add a dictionary to the list of running servers if running: @@ -319,11 +321,11 @@ class Controller: logger.info("Stopping All Servers") Console.info("Stopping All Servers") - for s in servers: - logger.info(f"Stopping Server ID {s['id']} - {s['name']}") - Console.info(f"Stopping Server ID {s['id']} - {s['name']}") + for server in servers: + logger.info(f"Stopping Server ID {server['id']} - {server['name']}") + Console.info(f"Stopping Server ID {server['id']} - {server['name']}") - self.stop_server(s["id"]) + self.stop_server(server["id"]) # let's wait 2 seconds to let everything flush out time.sleep(2) @@ -363,16 +365,18 @@ class Controller: try: # do a eula.txt - with open(os.path.join(server_dir, "eula.txt"), "w", encoding="utf-8") as f: - f.write("eula=false") - f.close() + with open( + os.path.join(server_dir, "eula.txt"), "w", encoding="utf-8" + ) as file: + file.write("eula=false") + file.close() # setup server.properties with the port with open( os.path.join(server_dir, "server.properties"), "w", encoding="utf-8" - ) as f: - f.write(f"server-port={port}") - f.close() + ) as file: + file.write(f"server-port={port}") + file.close() except Exception as e: logger.error(f"Unable to create required server files due to :{e}") @@ -465,9 +469,9 @@ class Controller: ) with open( os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8" - ) as f: - f.write(f"server-port={port}") - f.close() + ) as file: + file.write(f"server-port={port}") + file.close() full_jar_path = os.path.join(new_server_dir, server_jar) @@ -518,22 +522,22 @@ class Controller: new_server_dir.replace(" ", "^ ") backup_path.replace(" ", "^ ") - tempDir = Helpers.get_os_understandable_path(zip_path) + temp_dir = Helpers.get_os_understandable_path(zip_path) Helpers.ensure_dir_exists(new_server_dir) Helpers.ensure_dir_exists(backup_path) has_properties = False # extracts archive to temp directory - for item in os.listdir(tempDir): + for item in os.listdir(temp_dir): if str(item) == "server.properties": has_properties = True try: - if not os.path.isdir(os.path.join(tempDir, item)): + if not os.path.isdir(os.path.join(temp_dir, item)): FileHelpers.move_file( - os.path.join(tempDir, item), os.path.join(new_server_dir, item) + os.path.join(temp_dir, item), os.path.join(new_server_dir, item) ) else: FileHelpers.move_dir( - os.path.join(tempDir, item), os.path.join(new_server_dir, item) + os.path.join(temp_dir, item), os.path.join(new_server_dir, item) ) except Exception as ex: logger.error(f"ERROR IN ZIP IMPORT: {ex}") @@ -544,9 +548,9 @@ class Controller: ) with open( os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8" - ) as f: - f.write(f"server-port={port}") - f.close() + ) as file: + file.write(f"server-port={port}") + file.close() full_jar_path = os.path.join(new_server_dir, server_jar) @@ -615,9 +619,9 @@ class Controller: ) with open( os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8" - ) as f: - f.write(f"server-port={port}") - f.close() + ) as file: + file.write(f"server-port={port}") + file.close() full_jar_path = os.path.join(new_server_dir, server_exe) @@ -658,22 +662,22 @@ class Controller: new_server_dir.replace(" ", "^ ") backup_path.replace(" ", "^ ") - tempDir = Helpers.get_os_understandable_path(zip_path) + temp_dir = Helpers.get_os_understandable_path(zip_path) Helpers.ensure_dir_exists(new_server_dir) Helpers.ensure_dir_exists(backup_path) has_properties = False # extracts archive to temp directory - for item in os.listdir(tempDir): + for item in os.listdir(temp_dir): if str(item) == "server.properties": has_properties = True try: - if not os.path.isdir(os.path.join(tempDir, item)): + if not os.path.isdir(os.path.join(temp_dir, item)): FileHelpers.move_file( - os.path.join(tempDir, item), os.path.join(new_server_dir, item) + os.path.join(temp_dir, item), os.path.join(new_server_dir, item) ) else: FileHelpers.move_dir( - os.path.join(tempDir, item), os.path.join(new_server_dir, item) + os.path.join(temp_dir, item), os.path.join(new_server_dir, item) ) except Exception as ex: logger.error(f"ERROR IN ZIP IMPORT: {ex}") @@ -684,9 +688,9 @@ class Controller: ) with open( os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8" - ) as f: - f.write(f"server-port={port}") - f.close() + ) as file: + file.write(f"server-port={port}") + file.close() full_jar_path = os.path.join(new_server_dir, server_exe) @@ -723,7 +727,7 @@ class Controller: def rename_backup_dir(self, old_server_id, new_server_id, new_uuid): server_data = self.servers.get_server_data_by_id(old_server_id) old_bu_path = server_data["backup_path"] - Server_Perms_Controller.backup_role_swap(old_server_id, new_server_id) + ServerPermsController.backup_role_swap(old_server_id, new_server_id) if not Helpers.is_os_windows(): backup_path = Helpers.validate_traversal( self.helper.backup_path, old_bu_path @@ -758,7 +762,6 @@ class Controller: server_type: str, ): # put data in the db - new_id = self.servers.create_server( name, server_uuid, @@ -781,12 +784,12 @@ class Controller: os.path.join(server_dir, "crafty_managed.txt"), "w", encoding="utf-8", - ) as f: - f.write( + ) as file: + file.write( "The server is managed by Crafty Controller.\n " "Leave this directory/files alone please" ) - f.close() + file.close() except Exception as e: logger.error(f"Unable to create required server files due to :{e}") @@ -799,17 +802,17 @@ class Controller: def remove_server(self, server_id, files): counter = 0 - for s in self.servers_list: + for server in self.servers_list: # if this is the droid... im mean server we are looking for... - if str(s["server_id"]) == str(server_id): + if str(server["server_id"]) == str(server_id): server_data = self.get_server_data(server_id) server_name = server_data["server_name"] logger.info(f"Deleting Server: ID {server_id} | Name: {server_name} ") Console.info(f"Deleting Server: ID {server_id} | Name: {server_name} ") - srv_obj = s["server_obj"] + srv_obj = server["server_obj"] running = srv_obj.check_running() if running: @@ -839,7 +842,7 @@ class Controller: # Cleanup scheduled tasks try: - helpers_management.delete_scheduled_task_by_server(server_id) + HelpersManagement.delete_scheduled_task_by_server(server_id) except DoesNotExist: logger.info("No scheduled jobs exist. Continuing.") # remove the server from the DB @@ -852,8 +855,8 @@ class Controller: @staticmethod def clear_unexecuted_commands(): - helpers_management.clear_unexecuted_commands() + HelpersManagement.clear_unexecuted_commands() @staticmethod def clear_support_status(): - helper_users.clear_support_status() + HelperUsers.clear_support_status() diff --git a/app/classes/shared/main_models.py b/app/classes/shared/main_models.py index 52509534..1a0ef46a 100644 --- a/app/classes/shared/main_models.py +++ b/app/classes/shared/main_models.py @@ -1,13 +1,12 @@ import logging from playhouse.shortcuts import model_to_dict -# pylint: disable=unused-import -from app.classes.shared.helpers import Helpers +from app.classes.shared.helpers import Helpers # pylint: disable=unused-import logger = logging.getLogger(__name__) -class db_builder: +class DatabaseBuilder: def __init__(self, database, helper, users_helper): self.database = database self.helper = helper @@ -37,7 +36,7 @@ class db_builder: return True -class db_shortcuts: +class DatabaseShortcuts: # ********************************************************************************** # Generic Databse Methods # ********************************************************************************** diff --git a/app/classes/shared/migration.py b/app/classes/shared/migration.py index 6d1bfba8..9007442c 100644 --- a/app/classes/shared/migration.py +++ b/app/classes/shared/migration.py @@ -1,483 +1,483 @@ -# pylint: skip-file -from datetime import datetime -import logging -import typing as t -import sys -import os -import re -from functools import wraps -from functools import cached_property -import peewee -from playhouse.migrate import ( - SqliteMigrator, - Operation, - SQL, - SqliteDatabase, - make_index_name, -) - -from app.classes.shared.console import Console -from app.classes.shared.helpers import Helpers - -logger = logging.getLogger(__name__) - -MIGRATE_TABLE = "migratehistory" -MIGRATE_TEMPLATE = '''# Generated by database migrator -import peewee - -def migrate(migrator, db): - """ - Write your migrations here. - """ -{migrate} - -def rollback(migrator, db): - """ - Write your rollback migrations here. - """ -{rollback}''' - - -class MigrateHistory(peewee.Model): - """ - Presents the migration history in a database. - """ - - name = peewee.CharField(unique=True) - migrated_at = peewee.DateTimeField(default=datetime.utcnow) - - # noinspection PyTypeChecker - def __unicode__(self) -> str: - """ - String representation of this migration - """ - return self.name - - class Meta: - table_name = MIGRATE_TABLE - - -def get_model(method): - """ - Convert string to model class. - """ - - @wraps(method) - def wrapper(migrator, model, *args, **kwargs): - if isinstance(model, str): - return method(migrator, migrator.table_dict[model], *args, **kwargs) - return method(migrator, model, *args, **kwargs) - - return wrapper - - -# noinspection PyProtectedMember -class Migrator(object): - def __init__(self, database: t.Union[peewee.Database, peewee.Proxy]): - """ - Initializes the migrator - """ - if isinstance(database, peewee.Proxy): - database = database.obj - self.database: SqliteDatabase = database - self.table_dict: t.Dict[str, peewee.Model] = {} - self.operations: t.List[t.Union[Operation, callable]] = [] - self.migrator = SqliteMigrator(database) - - def run(self): - """ - Runs operations. - """ - for op in self.operations: - if isinstance(op, Operation): - op.run() - else: - op() - self.clean() - - def clean(self): - """ - Cleans the operations. - """ - self.operations = list() - - def sql(self, sql: str, *params): - """ - Executes raw SQL. - """ - self.operations.append(SQL(sql, *params)) - - def create_table(self, model: peewee.Model) -> peewee.Model: - """ - Creates model and table in database. - """ - self.table_dict[model._meta.table_name] = model - model._meta.database = self.database - self.operations.append(model.create_table) - return model - - @get_model - def drop_table(self, model: peewee.Model): - """ - Drops model and table from database. - """ - del self.table_dict[model._meta.table_name] - self.operations.append(lambda: model.drop_table(cascade=False)) - - @get_model - def add_columns(self, model: peewee.Model, **fields: peewee.Field) -> peewee.Model: - """ - Creates new fields. - """ - for name, field in fields.items(): - model._meta.add_field(name, field) - self.operations.append( - self.migrator.add_column( - model._meta.table_name, field.column_name, field - ) - ) - if field.unique: - self.operations.append( - self.migrator.add_index( - model._meta.table_name, (field.column_name,), unique=True - ) - ) - return model - - @get_model - def drop_columns(self, model: peewee.Model, names: str) -> peewee.Model: - """ - Removes fields from model. - """ - fields = [field for field in model._meta.fields.values() if field.name in names] - for field in fields: - self.__del_field__(model, field) - if field.unique: - # Drop unique index - index_name = make_index_name( - model._meta.table_name, [field.column_name] - ) - self.operations.append( - self.migrator.drop_index(model._meta.table_name, index_name) - ) - self.operations.append( - self.migrator.drop_column( - model._meta.table_name, field.column_name, cascade=False - ) - ) - return model - - def __del_field__(self, model: peewee.Model, field: peewee.Field): - """ - Deletes field from model. - """ - model._meta.remove_field(field.name) - delattr(model, field.name) - if isinstance(field, peewee.ForeignKeyField): - obj_id_name = field.column_name - if field.column_name == field.name: - obj_id_name += "_id" - delattr(model, obj_id_name) - delattr(field.rel_model, field.backref) - - @get_model - def rename_column( - self, model: peewee.Model, old_name: str, new_name: str - ) -> peewee.Model: - """ - Renames field in model. - """ - field = model._meta.fields[old_name] - if isinstance(field, peewee.ForeignKeyField): - old_name = field.column_name - self.__del_field__(model, field) - field.name = field.column_name = new_name - model._meta.add_field(new_name, field) - if isinstance(field, peewee.ForeignKeyField): - field.column_name = new_name = field.column_name + "_id" - self.operations.append( - self.migrator.rename_column(model._meta.table_name, old_name, new_name) - ) - return model - - @get_model - def rename_table(self, model: peewee.Model, new_name: str) -> peewee.Model: - """ - Renames table in database. - """ - old_name = model._meta.table_name - del self.table_dict[model._meta.table_name] - model._meta.table_name = new_name - self.table_dict[model._meta.table_name] = model - self.operations.append(self.migrator.rename_table(old_name, new_name)) - return model - - @get_model - def add_index( - self, model: peewee.Model, *columns: str, unique=False - ) -> peewee.Model: - """Create indexes.""" - model._meta.indexes.append((columns, unique)) - columns_ = [] - for col in columns: - field = model._meta.fields.get(col) - - if len(columns) == 1: - field.unique = unique - field.index = not unique - - if isinstance(field, peewee.ForeignKeyField): - col = col + "_id" - - columns_.append(col) - self.operations.append( - self.migrator.add_index(model._meta.table_name, columns_, unique=unique) - ) - return model - - @get_model - def drop_index(self, model: peewee.Model, *columns: str) -> peewee.Model: - """Drop indexes.""" - columns_ = [] - for col in columns: - field = model._meta.fields.get(col) - if not field: - continue - - if len(columns) == 1: - field.unique = field.index = False - - if isinstance(field, peewee.ForeignKeyField): - col = col + "_id" - columns_.append(col) - index_name = make_index_name(model._meta.table_name, columns_) - model._meta.indexes = [ - (cols, _) for (cols, _) in model._meta.indexes if columns != cols - ] - self.operations.append( - self.migrator.drop_index(model._meta.table_name, index_name) - ) - return model - - @get_model - def add_not_null(self, model: peewee.Model, *names: str) -> peewee.Model: - """Add not null.""" - for name in names: - field = model._meta.fields[name] - field.null = False - self.operations.append( - self.migrator.add_not_null(model._meta.table_name, field.column_name) - ) - return model - - @get_model - def drop_not_null(self, model: peewee.Model, *names: str) -> peewee.Model: - """Drop not null.""" - for name in names: - field = model._meta.fields[name] - field.null = True - self.operations.append( - self.migrator.drop_not_null(model._meta.table_name, field.column_name) - ) - return model - - @get_model - def add_default( - self, model: peewee.Model, name: str, default: t.Any - ) -> peewee.Model: - """Add default.""" - field = model._meta.fields[name] - model._meta.defaults[field] = field.default = default - self.operations.append( - self.migrator.apply_default(model._meta.table_name, name, field) - ) - return model - - -# noinspection PyProtectedMember -class MigrationManager(object): - filemask = re.compile(r"[\d]+_[^\.]+\.py$") - - def __init__(self, database: t.Union[peewee.Database, peewee.Proxy], helper): - """ - Initializes the migration manager. - """ - if not isinstance(database, (peewee.Database, peewee.Proxy)): - raise RuntimeError("Invalid database: {}".format(database)) - self.database = database - self.helper = helper - - @cached_property - def model(self) -> t.Type[MigrateHistory]: - """ - Initialize and cache the MigrationHistory model. - """ - MigrateHistory._meta.database = self.database - MigrateHistory._meta.table_name = "migratehistory" - MigrateHistory._meta.schema = None - MigrateHistory.create_table(True) - return MigrateHistory - - @property - def done(self) -> t.List[str]: - """ - Scans migrations in the database. - """ - return [mm.name for mm in self.model.select().order_by(self.model.id)] - - @property - def todo(self): - """ - Scans migrations in the file system. - """ - if not os.path.exists(self.helper.migration_dir): - logger.warning( - "Migration directory: {} does not exist.".format( - self.helper.migration_dir - ) - ) - os.makedirs(self.helper.migration_dir) - return sorted( - f[:-3] - for f in os.listdir(self.helper.migration_dir) - if self.filemask.match(f) - ) - - @property - def diff(self) -> t.List[str]: - """ - Calculates difference between the filesystem and the database. - """ - done = set(self.done) - return [name for name in self.todo if name not in done] - - @cached_property - def migrator(self) -> Migrator: - """ - Create migrator and setup it with fake migrations. - """ - migrator = Migrator(self.database) - for name in self.done: - self.up_one(name, migrator, True) - return migrator - - def compile(self, name, migrate="", rollback=""): - """ - Compiles a migration. - """ - name = datetime.utcnow().strftime("%Y%m%d%H%M%S") + "_" + name - filename = name + ".py" - path = os.path.join(self.helper.migration_dir, filename) - with open(path, "w") as f: - f.write( - MIGRATE_TEMPLATE.format( - migrate=migrate, rollback=rollback, name=filename - ) - ) - - return name - - def create(self, name: str = "auto", auto: bool = False) -> t.Optional[str]: - """ - Creates a migration. - """ - migrate = rollback = "" - if auto: - raise NotImplementedError - - logger.info('Creating migration "{}"'.format(name)) - name = self.compile(name, migrate, rollback) - logger.info('Migration has been created as "{}"'.format(name)) - return name - - def clear(self): - """Clear migrations.""" - self.model.delete().execute() - - def up(self, name: t.Optional[str] = None): - """ - Runs all unapplied migrations. - """ - logger.info("Starting migrations") - Console.info("Starting migrations") - - done = [] - diff = self.diff - if not diff: - logger.info("There is nothing to migrate") - Console.info("There is nothing to migrate") - return done - - migrator = self.migrator - for mname in diff: - done.append(self.up_one(mname, self.migrator)) - if name and name == mname: - break - - return done - - def read(self, name: str): - """ - Reads a migration from a file. - """ - call_params = dict() - if Helpers.is_os_windows() and sys.version_info >= (3, 0): - # if system is windows - force utf-8 encoding - call_params["encoding"] = "utf-8" - with open( - os.path.join(self.helper.migration_dir, name + ".py"), **call_params - ) as f: - code = f.read() - scope = {} - code = compile(code, "", "exec", dont_inherit=True) - exec(code, scope, None) - return scope.get("migrate", lambda m, d: None), scope.get( - "rollback", lambda m, d: None - ) - - def up_one( - self, name: str, migrator: Migrator, fake: bool = False, rollback: bool = False - ) -> str: - """ - Runs a migration with a given name. - """ - try: - migrate_fn, rollback_fn = self.read(name) - if fake: - migrate_fn(migrator, self.database) - migrator.clean() - return name - with self.database.transaction(): - if rollback: - logger.info('Rolling back "{}"'.format(name)) - rollback_fn(migrator, self.database) - migrator.run() - self.model.delete().where(self.model.name == name).execute() - else: - logger.info('Migrate "{}"'.format(name)) - migrate_fn(migrator, self.database) - migrator.run() - if name not in self.done: - self.model.create(name=name) - - logger.info('Done "{}"'.format(name)) - return name - - except Exception: - self.database.rollback() - operation_name = "Rollback" if rollback else "Migration" - logger.exception("{} failed: {}".format(operation_name, name)) - raise - - def down(self): - """ - Rolls back migrations. - """ - if not self.done: - raise RuntimeError("No migrations are found.") - - name = self.done[-1] - - migrator = self.migrator - self.up_one(name, migrator, False, True) - logger.warning("Rolled back migration: {}".format(name)) +# pylint: skip-file +from datetime import datetime +import logging +import typing as t +import sys +import os +import re +from functools import wraps +from functools import cached_property +import peewee +from playhouse.migrate import ( + SqliteMigrator, + Operation, + SQL, + SqliteDatabase, + make_index_name, +) + +from app.classes.shared.console import Console +from app.classes.shared.helpers import Helpers + +logger = logging.getLogger(__name__) + +MIGRATE_TABLE = "migratehistory" +MIGRATE_TEMPLATE = '''# Generated by database migrator +import peewee + +def migrate(migrator, db): + """ + Write your migrations here. + """ +{migrate} + +def rollback(migrator, db): + """ + Write your rollback migrations here. + """ +{rollback}''' + + +class MigrateHistory(peewee.Model): + """ + Presents the migration history in a database. + """ + + name = peewee.CharField(unique=True) + migrated_at = peewee.DateTimeField(default=datetime.utcnow) + + # noinspection PyTypeChecker + def __unicode__(self) -> str: + """ + String representation of this migration + """ + return self.name + + class Meta: + table_name = MIGRATE_TABLE + + +def get_model(method): + """ + Convert string to model class. + """ + + @wraps(method) + def wrapper(migrator, model, *args, **kwargs): + if isinstance(model, str): + return method(migrator, migrator.table_dict[model], *args, **kwargs) + return method(migrator, model, *args, **kwargs) + + return wrapper + + +# noinspection PyProtectedMember +class Migrator(object): + def __init__(self, database: t.Union[peewee.Database, peewee.Proxy]): + """ + Initializes the migrator + """ + if isinstance(database, peewee.Proxy): + database = database.obj + self.database: SqliteDatabase = database + self.table_dict: t.Dict[str, peewee.Model] = {} + self.operations: t.List[t.Union[Operation, callable]] = [] + self.migrator = SqliteMigrator(database) + + def run(self): + """ + Runs operations. + """ + for op in self.operations: + if isinstance(op, Operation): + op.run() + else: + op() + self.clean() + + def clean(self): + """ + Cleans the operations. + """ + self.operations = list() + + def sql(self, sql: str, *params): + """ + Executes raw SQL. + """ + self.operations.append(SQL(sql, *params)) + + def create_table(self, model: peewee.Model) -> peewee.Model: + """ + Creates model and table in database. + """ + self.table_dict[model._meta.table_name] = model + model._meta.database = self.database + self.operations.append(model.create_table) + return model + + @get_model + def drop_table(self, model: peewee.Model): + """ + Drops model and table from database. + """ + del self.table_dict[model._meta.table_name] + self.operations.append(lambda: model.drop_table(cascade=False)) + + @get_model + def add_columns(self, model: peewee.Model, **fields: peewee.Field) -> peewee.Model: + """ + Creates new fields. + """ + for name, field in fields.items(): + model._meta.add_field(name, field) + self.operations.append( + self.migrator.add_column( + model._meta.table_name, field.column_name, field + ) + ) + if field.unique: + self.operations.append( + self.migrator.add_index( + model._meta.table_name, (field.column_name,), unique=True + ) + ) + return model + + @get_model + def drop_columns(self, model: peewee.Model, names: str) -> peewee.Model: + """ + Removes fields from model. + """ + fields = [field for field in model._meta.fields.values() if field.name in names] + for field in fields: + self.__del_field__(model, field) + if field.unique: + # Drop unique index + index_name = make_index_name( + model._meta.table_name, [field.column_name] + ) + self.operations.append( + self.migrator.drop_index(model._meta.table_name, index_name) + ) + self.operations.append( + self.migrator.drop_column( + model._meta.table_name, field.column_name, cascade=False + ) + ) + return model + + def __del_field__(self, model: peewee.Model, field: peewee.Field): + """ + Deletes field from model. + """ + model._meta.remove_field(field.name) + delattr(model, field.name) + if isinstance(field, peewee.ForeignKeyField): + obj_id_name = field.column_name + if field.column_name == field.name: + obj_id_name += "_id" + delattr(model, obj_id_name) + delattr(field.rel_model, field.backref) + + @get_model + def rename_column( + self, model: peewee.Model, old_name: str, new_name: str + ) -> peewee.Model: + """ + Renames field in model. + """ + field = model._meta.fields[old_name] + if isinstance(field, peewee.ForeignKeyField): + old_name = field.column_name + self.__del_field__(model, field) + field.name = field.column_name = new_name + model._meta.add_field(new_name, field) + if isinstance(field, peewee.ForeignKeyField): + field.column_name = new_name = field.column_name + "_id" + self.operations.append( + self.migrator.rename_column(model._meta.table_name, old_name, new_name) + ) + return model + + @get_model + def rename_table(self, model: peewee.Model, new_name: str) -> peewee.Model: + """ + Renames table in database. + """ + old_name = model._meta.table_name + del self.table_dict[model._meta.table_name] + model._meta.table_name = new_name + self.table_dict[model._meta.table_name] = model + self.operations.append(self.migrator.rename_table(old_name, new_name)) + return model + + @get_model + def add_index( + self, model: peewee.Model, *columns: str, unique=False + ) -> peewee.Model: + """Create indexes.""" + model._meta.indexes.append((columns, unique)) + columns_ = [] + for col in columns: + field = model._meta.fields.get(col) + + if len(columns) == 1: + field.unique = unique + field.index = not unique + + if isinstance(field, peewee.ForeignKeyField): + col = col + "_id" + + columns_.append(col) + self.operations.append( + self.migrator.add_index(model._meta.table_name, columns_, unique=unique) + ) + return model + + @get_model + def drop_index(self, model: peewee.Model, *columns: str) -> peewee.Model: + """Drop indexes.""" + columns_ = [] + for col in columns: + field = model._meta.fields.get(col) + if not field: + continue + + if len(columns) == 1: + field.unique = field.index = False + + if isinstance(field, peewee.ForeignKeyField): + col = col + "_id" + columns_.append(col) + index_name = make_index_name(model._meta.table_name, columns_) + model._meta.indexes = [ + (cols, _) for (cols, _) in model._meta.indexes if columns != cols + ] + self.operations.append( + self.migrator.drop_index(model._meta.table_name, index_name) + ) + return model + + @get_model + def add_not_null(self, model: peewee.Model, *names: str) -> peewee.Model: + """Add not null.""" + for name in names: + field = model._meta.fields[name] + field.null = False + self.operations.append( + self.migrator.add_not_null(model._meta.table_name, field.column_name) + ) + return model + + @get_model + def drop_not_null(self, model: peewee.Model, *names: str) -> peewee.Model: + """Drop not null.""" + for name in names: + field = model._meta.fields[name] + field.null = True + self.operations.append( + self.migrator.drop_not_null(model._meta.table_name, field.column_name) + ) + return model + + @get_model + def add_default( + self, model: peewee.Model, name: str, default: t.Any + ) -> peewee.Model: + """Add default.""" + field = model._meta.fields[name] + model._meta.defaults[field] = field.default = default + self.operations.append( + self.migrator.apply_default(model._meta.table_name, name, field) + ) + return model + + +# noinspection PyProtectedMember +class MigrationManager(object): + filemask = re.compile(r"[\d]+_[^\.]+\.py$") + + def __init__(self, database: t.Union[peewee.Database, peewee.Proxy], helper): + """ + Initializes the migration manager. + """ + if not isinstance(database, (peewee.Database, peewee.Proxy)): + raise RuntimeError("Invalid database: {}".format(database)) + self.database = database + self.helper = helper + + @cached_property + def model(self) -> t.Type[MigrateHistory]: + """ + Initialize and cache the MigrationHistory model. + """ + MigrateHistory._meta.database = self.database + MigrateHistory._meta.table_name = "migratehistory" + MigrateHistory._meta.schema = None + MigrateHistory.create_table(True) + return MigrateHistory + + @property + def done(self) -> t.List[str]: + """ + Scans migrations in the database. + """ + return [mm.name for mm in self.model.select().order_by(self.model.id)] + + @property + def todo(self): + """ + Scans migrations in the file system. + """ + if not os.path.exists(self.helper.migration_dir): + logger.warning( + "Migration directory: {} does not exist.".format( + self.helper.migration_dir + ) + ) + os.makedirs(self.helper.migration_dir) + return sorted( + f[:-3] + for f in os.listdir(self.helper.migration_dir) + if self.filemask.match(f) + ) + + @property + def diff(self) -> t.List[str]: + """ + Calculates difference between the filesystem and the database. + """ + done = set(self.done) + return [name for name in self.todo if name not in done] + + @cached_property + def migrator(self) -> Migrator: + """ + Create migrator and setup it with fake migrations. + """ + migrator = Migrator(self.database) + for name in self.done: + self.up_one(name, migrator, True) + return migrator + + def compile(self, name, migrate="", rollback=""): + """ + Compiles a migration. + """ + name = datetime.utcnow().strftime("%Y%m%d%H%M%S") + "_" + name + filename = name + ".py" + path = os.path.join(self.helper.migration_dir, filename) + with open(path, "w") as f: + f.write( + MIGRATE_TEMPLATE.format( + migrate=migrate, rollback=rollback, name=filename + ) + ) + + return name + + def create(self, name: str = "auto", auto: bool = False) -> t.Optional[str]: + """ + Creates a migration. + """ + migrate = rollback = "" + if auto: + raise NotImplementedError + + logger.info('Creating migration "{}"'.format(name)) + name = self.compile(name, migrate, rollback) + logger.info('Migration has been created as "{}"'.format(name)) + return name + + def clear(self): + """Clear migrations.""" + self.model.delete().execute() + + def up(self, name: t.Optional[str] = None): + """ + Runs all unapplied migrations. + """ + logger.info("Starting migrations") + Console.info("Starting migrations") + + done = [] + diff = self.diff + if not diff: + logger.info("There is nothing to migrate") + Console.info("There is nothing to migrate") + return done + + migrator = self.migrator + for mname in diff: + done.append(self.up_one(mname, self.migrator)) + if name and name == mname: + break + + return done + + def read(self, name: str): + """ + Reads a migration from a file. + """ + call_params = dict() + if Helpers.is_os_windows() and sys.version_info >= (3, 0): + # if system is windows - force utf-8 encoding + call_params["encoding"] = "utf-8" + with open( + os.path.join(self.helper.migration_dir, name + ".py"), **call_params + ) as f: + code = f.read() + scope = {} + code = compile(code, "", "exec", dont_inherit=True) + exec(code, scope, None) + return scope.get("migrate", lambda m, d: None), scope.get( + "rollback", lambda m, d: None + ) + + def up_one( + self, name: str, migrator: Migrator, fake: bool = False, rollback: bool = False + ) -> str: + """ + Runs a migration with a given name. + """ + try: + migrate_fn, rollback_fn = self.read(name) + if fake: + migrate_fn(migrator, self.database) + migrator.clean() + return name + with self.database.transaction(): + if rollback: + logger.info('Rolling back "{}"'.format(name)) + rollback_fn(migrator, self.database) + migrator.run() + self.model.delete().where(self.model.name == name).execute() + else: + logger.info('Migrate "{}"'.format(name)) + migrate_fn(migrator, self.database) + migrator.run() + if name not in self.done: + self.model.create(name=name) + + logger.info('Done "{}"'.format(name)) + return name + + except Exception: + self.database.rollback() + operation_name = "Rollback" if rollback else "Migration" + logger.exception("{} failed: {}".format(operation_name, name)) + raise + + def down(self): + """ + Rolls back migrations. + """ + if not self.done: + raise RuntimeError("No migrations are found.") + + name = self.done[-1] + + migrator = self.migrator + self.up_one(name, migrator, False, True) + logger.warning("Rolled back migration: {}".format(name)) diff --git a/app/classes/shared/permission_helper.py b/app/classes/shared/permission_helper.py index 686b738b..115faef7 100644 --- a/app/classes/shared/permission_helper.py +++ b/app/classes/shared/permission_helper.py @@ -3,18 +3,21 @@ from enum import Enum class PermissionHelper: @staticmethod - def both_have_perm(a: str, b: str, permission_tested: Enum): + def both_have_perm( + permission_mask_a: str, permission_mask_b: str, permission_tested: Enum + ): return PermissionHelper.combine_perm_bool( - a[permission_tested.value], b[permission_tested.value] + permission_mask_a[permission_tested.value], + permission_mask_b[permission_tested.value], ) @staticmethod - def combine_perm(a: str, b: str) -> str: - return "1" if (a == "1" and b == "1") else "0" + def combine_perm(permission_mask_a: str, permission_mask_b: str) -> str: + return "1" if (permission_mask_a == "1" and permission_mask_b == "1") else "0" @staticmethod - def combine_perm_bool(a: str, b: str) -> bool: - return a == "1" and b == "1" + def combine_perm_bool(permission_mask_a: str, permission_mask_b: str) -> bool: + return permission_mask_a == "1" and permission_mask_b == "1" @staticmethod def combine_masks(permission_mask_a: str, permission_mask_b: str) -> str: diff --git a/app/classes/shared/server.py b/app/classes/shared/server.py index 772ab969..af0073cf 100644 --- a/app/classes/shared/server.py +++ b/app/classes/shared/server.py @@ -17,10 +17,10 @@ from apscheduler.schedulers.background import BackgroundScheduler from app.classes.minecraft.stats import Stats from app.classes.minecraft.mc_ping import ping, ping_bedrock -from app.classes.models.servers import Server_Stats, helper_servers -from app.classes.models.management import helpers_management -from app.classes.models.users import helper_users -from app.classes.models.server_permissions import Permissions_Servers +from app.classes.models.servers import ServerStats, HelperServers +from app.classes.models.management import HelpersManagement +from app.classes.models.users import HelperUsers +from app.classes.models.server_permissions import PermissionsServers from app.classes.shared.console import Console from app.classes.shared.helpers import Helpers from app.classes.shared.file_helpers import FileHelpers @@ -118,28 +118,28 @@ class Server: ) self.is_backingup = False # Reset crash and update at initialization - helper_servers.server_crash_reset(self.server_id) - helper_servers.set_update(self.server_id, False) + HelperServers.server_crash_reset(self.server_id) + HelperServers.set_update(self.server_id, False) # ********************************************************************************** # Minecraft Server Management # ********************************************************************************** def reload_server_settings(self): - server_data = helper_servers.get_server_data_by_id(self.server_id) + server_data = HelperServers.get_server_data_by_id(self.server_id) self.settings = server_data def do_server_setup(self, server_data_obj): - serverId = server_data_obj["server_id"] - serverName = server_data_obj["server_name"] - autoStart = server_data_obj["auto_start"] + server_id = server_data_obj["server_id"] + server_name = server_data_obj["server_name"] + auto_start = server_data_obj["auto_start"] logger.info( - f"Creating Server object: {serverId} | " - f"Server Name: {serverName} | " - f"Auto Start: {autoStart}" + f"Creating Server object: {server_id} | " + f"Server Name: {server_name} | " + f"Auto Start: {auto_start}" ) - self.server_id = serverId - self.name = serverName + self.server_id = server_id + self.name = server_name self.settings = server_data_obj self.record_server_stats() @@ -163,7 +163,7 @@ class Server: Console.info(f"Starting server ID: {self.server_id} - {self.name}") logger.info(f"Starting server ID: {self.server_id} - {self.name}") # Sets waiting start to false since we're attempting to start the server. - helper_servers.set_waiting_start(self.server_id, False) + HelperServers.set_waiting_start(self.server_id, False) self.run_threaded_server(None) # remove the scheduled job since it's ran @@ -228,9 +228,9 @@ class Server: if not user_id: user_lang = self.helper.get_setting("language") else: - user_lang = helper_users.get_user_lang_by_id(user_id) + user_lang = HelperUsers.get_user_lang_by_id(user_id) - if helper_servers.get_download_status(self.server_id): + if HelperServers.get_download_status(self.server_id): if user_id: self.helper.websocket_helper.broadcast_user( user_id, @@ -310,7 +310,7 @@ class Server: f = open( os.path.join( self.server_path, - helper_servers.get_server_data_by_id(self.server_id)["executable"], + HelperServers.get_server_data_by_id(self.server_id)["executable"], ), "r", encoding="utf-8", @@ -332,7 +332,7 @@ class Server: if ( not Helpers.is_os_windows() - and helper_servers.get_server_type_by_id(self.server_id) + and HelperServers.get_server_type_by_id(self.server_id) == "minecraft-bedrock" ): logger.info( @@ -413,7 +413,7 @@ class Server: ).start() self.is_crashed = False - helper_servers.server_crash_reset(self.server_id) + HelperServers.server_crash_reset(self.server_id) self.start_time = str(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")) @@ -421,7 +421,7 @@ class Server: logger.info(f"Server {self.name} running with PID {self.process.pid}") Console.info(f"Server {self.name} running with PID {self.process.pid}") self.is_crashed = False - helper_servers.server_crash_reset(self.server_id) + HelperServers.server_crash_reset(self.server_id) self.record_server_stats() check_internet_thread = threading.Thread( target=self.check_internet_thread, @@ -434,9 +434,9 @@ class Server: ) check_internet_thread.start() # Checks if this is the servers first run. - if helper_servers.get_first_run(self.server_id): - helper_servers.set_first_run(self.server_id) - loc_server_port = helper_servers.get_server_stats_by_id(self.server_id)[ + if HelperServers.get_first_run(self.server_id): + HelperServers.set_first_run(self.server_id) + loc_server_port = HelperServers.get_server_stats_by_id(self.server_id)[ "server_port" ] # Sends port reminder message. @@ -449,14 +449,14 @@ class Server: ).format(self.name, loc_server_port) }, ) - server_users = Permissions_Servers.get_server_user_list(self.server_id) + server_users = PermissionsServers.get_server_user_list(self.server_id) for user in server_users: if user != user_id: self.helper.websocket_helper.broadcast_user( user, "send_start_reload", {} ) else: - server_users = Permissions_Servers.get_server_user_list(self.server_id) + server_users = PermissionsServers.get_server_user_list(self.server_id) for user in server_users: self.helper.websocket_helper.broadcast_user( user, "send_start_reload", {} @@ -554,17 +554,17 @@ class Server: logger.info(f"Can't stop server {self.name} if it's not running") Console.info(f"Can't stop server {self.name} if it's not running") return - x = 0 + i = 0 # caching the name and pid number server_name = self.name server_pid = self.process.pid while running: - x = x + 1 + i += 1 logstr = ( f"Server {server_name} is still running " - f"- waiting 2s to see if it stops ({int(60-(x*2))} " + f"- waiting 2s to see if it stops ({int(60-(i*2))} " f"seconds until force close)" ) logger.info(logstr) @@ -573,7 +573,7 @@ class Server: time.sleep(2) # if we haven't closed in 60 seconds, let's just slam down on the PID - if x >= 30: + if i >= 30: logger.info( f"Server {server_name} is still running - Forcing the process down" ) @@ -587,7 +587,7 @@ class Server: # massive resetting of variables self.cleanup_server_object() - server_users = Permissions_Servers.get_server_user_list(self.server_id) + server_users = PermissionsServers.get_server_user_list(self.server_id) # remove the stats polling job since server is stopped self.server_scheduler.remove_job("stats_" + str(self.server_id)) @@ -718,7 +718,7 @@ class Server: self.server_scheduler.remove_job("c_" + str(self.server_id)) return - helper_servers.sever_crashed(self.server_id) + HelperServers.sever_crashed(self.server_id) # if we haven't tried to restart more 3 or more times if self.restart_count <= 3: @@ -742,7 +742,7 @@ class Server: self.restart_count = 0 self.is_crashed = True - helper_servers.sever_crashed(self.server_id) + HelperServers.sever_crashed(self.server_id) # cancel the watcher task self.server_scheduler.remove_job("c_" + str(self.server_id)) @@ -806,17 +806,17 @@ class Server: {"percent": 0, "total_files": 0}, ) logger.info(f"Starting server {self.name} (ID {self.server_id}) backup") - server_users = Permissions_Servers.get_server_user_list(self.server_id) + server_users = PermissionsServers.get_server_user_list(self.server_id) for user in server_users: self.helper.websocket_helper.broadcast_user( user, "notification", self.helper.translation.translate( - "notify", "backupStarted", helper_users.get_user_lang_by_id(user) + "notify", "backupStarted", HelperUsers.get_user_lang_by_id(user) ).format(self.name), ) time.sleep(3) - conf = helpers_management.get_backup_config(self.server_id) + conf = HelpersManagement.get_backup_config(self.server_id) self.helper.ensure_dir_exists(self.settings["backup_path"]) try: backup_filename = ( @@ -829,17 +829,17 @@ class Server: f"at '{backup_filename}'" ) - tempDir = tempfile.mkdtemp() + temp_dir = tempfile.mkdtemp() self.server_scheduler.add_job( self.backup_status, "interval", seconds=1, id="backup_" + str(self.server_id), - args=[tempDir + "/", backup_filename + ".zip"], + args=[temp_dir + "/", backup_filename + ".zip"], ) # pylint: disable=unexpected-keyword-arg - FileHelpers.copy_dir(self.server_path, tempDir, dirs_exist_ok=True) - excluded_dirs = helpers_management.get_excluded_backup_dirs(self.server_id) + FileHelpers.copy_dir(self.server_path, temp_dir, dirs_exist_ok=True) + excluded_dirs = HelpersManagement.get_excluded_backup_dirs(self.server_id) server_dir = Helpers.get_os_understandable_path(self.settings["path"]) for my_dir in excluded_dirs: @@ -848,7 +848,7 @@ class Server: # only deleting excluded dirs from the temp path # and not the server path excluded_dir = Helpers.get_os_understandable_path(my_dir).replace( - server_dir, Helpers.get_os_understandable_path(tempDir) + server_dir, Helpers.get_os_understandable_path(temp_dir) ) # Next, check to see if it is a directory if os.path.isdir(excluded_dir): @@ -863,14 +863,14 @@ class Server: "Found compress backup to be true. Calling compressed archive" ) FileHelpers.make_compressed_archive( - Helpers.get_os_understandable_path(backup_filename), tempDir + Helpers.get_os_understandable_path(backup_filename), temp_dir ) else: logger.debug( "Found compress backup to be false. Calling NON-compressed archive" ) FileHelpers.make_archive( - Helpers.get_os_understandable_path(backup_filename), tempDir + Helpers.get_os_understandable_path(backup_filename), temp_dir ) while ( @@ -884,7 +884,7 @@ class Server: os.remove(Helpers.get_os_understandable_path(oldfile_path)) self.is_backingup = False - FileHelpers.del_dirs(tempDir) + FileHelpers.del_dirs(temp_dir) logger.info(f"Backup of server: {self.name} completed") self.server_scheduler.remove_job("backup_" + str(self.server_id)) results = {"percent": 100, "total_files": 0, "current_file": 0} @@ -895,7 +895,7 @@ class Server: "backup_status", results, ) - server_users = Permissions_Servers.get_server_user_list(self.server_id) + server_users = PermissionsServers.get_server_user_list(self.server_id) for user in server_users: self.helper.websocket_helper.broadcast_user( user, @@ -903,7 +903,7 @@ class Server: self.helper.translation.translate( "notify", "backupComplete", - helper_users.get_user_lang_by_id(user), + HelperUsers.get_user_lang_by_id(user), ).format(self.name), ) time.sleep(3) @@ -972,7 +972,7 @@ class Server: return [] def jar_update(self): - helper_servers.set_update(self.server_id, True) + HelperServers.set_update(self.server_id, True) update_thread = threading.Thread( target=self.a_jar_update, daemon=True, name=f"exe_update_{self.name}" ) @@ -980,24 +980,24 @@ class Server: def check_update(self): - if helper_servers.get_server_stats_by_id(self.server_id)["updating"]: + if HelperServers.get_server_stats_by_id(self.server_id)["updating"]: return True else: return False def a_jar_update(self): - wasStarted = "-1" + was_started = "-1" self.backup_server() # checks if server is running. Calls shutdown if it is running. if self.check_running(): - wasStarted = True + was_started = True logger.info( f"Server with PID {self.process.pid} is running. " f"Sending shutdown command" ) self.stop_threaded_server() else: - wasStarted = False + was_started = False if len(self.helper.websocket_helper.clients) > 0: # There are clients self.check_update() @@ -1010,7 +1010,7 @@ class Server: { "isUpdating": self.check_update(), "server_id": self.server_id, - "wasRunning": wasStarted, + "wasRunning": was_started, "string": message, }, ) @@ -1053,15 +1053,15 @@ class Server: self.settings["executable_update_url"], current_executable ) - while helper_servers.get_server_stats_by_id(self.server_id)["updating"]: + while HelperServers.get_server_stats_by_id(self.server_id)["updating"]: if downloaded and not self.is_backingup: logger.info("Executable updated successfully. Starting Server") - helper_servers.set_update(self.server_id, False) + HelperServers.set_update(self.server_id, False) if len(self.helper.websocket_helper.clients) > 0: # There are clients self.check_update() - server_users = Permissions_Servers.get_server_user_list( + server_users = PermissionsServers.get_server_user_list( self.server_id ) for user in server_users: @@ -1077,13 +1077,13 @@ class Server: { "isUpdating": self.check_update(), "server_id": self.server_id, - "wasRunning": wasStarted, + "wasRunning": was_started, }, ) self.helper.websocket_helper.broadcast_page( "/panel/dashboard", "send_start_reload", {} ) - server_users = Permissions_Servers.get_server_user_list(self.server_id) + server_users = PermissionsServers.get_server_user_list(self.server_id) for user in server_users: self.helper.websocket_helper.broadcast_user( user, @@ -1098,11 +1098,11 @@ class Server: "Executable update finished for " + self.name, self.settings["server_ip"], ) - if wasStarted: + if was_started: self.start_server() elif not downloaded and not self.is_backingup: time.sleep(5) - server_users = Permissions_Servers.get_server_user_list(self.server_id) + server_users = PermissionsServers.get_server_user_list(self.server_id) for user in server_users: self.helper.websocket_helper.broadcast_user( user, @@ -1194,7 +1194,7 @@ class Server: logger.info("Getting Stats for Server " + self.name + " ...") server_id = self.server_id - server = helper_servers.get_server_data_by_id(server_id) + server = HelperServers.get_server_data_by_id(server_id) logger.debug(f"Getting stats for server: {server_id}") @@ -1213,7 +1213,7 @@ class Server: server_name = server.get("server_name", f"ID#{server_id}") logger.debug(f"Pinging server '{server}' on {internal_ip}:{server_port}") - if helper_servers.get_server_type_by_id(server_id) == "minecraft-bedrock": + if HelperServers.get_server_type_by_id(server_id) == "minecraft-bedrock": int_mc_ping = ping_bedrock(internal_ip, int(server_port)) else: int_mc_ping = ping(internal_ip, int(server_port)) @@ -1225,10 +1225,10 @@ class Server: if int_mc_ping: int_data = True if ( - helper_servers.get_server_type_by_id(server["server_id"]) + HelperServers.get_server_type_by_id(server["server_id"]) == "minecraft-bedrock" ): - ping_data = Stats.parse_server_RakNet_ping(int_mc_ping) + ping_data = Stats.parse_server_raknet_ping(int_mc_ping) else: ping_data = Stats.parse_server_ping(int_mc_ping) # Makes sure we only show stats when a server is online @@ -1274,7 +1274,7 @@ class Server: def get_server_players(self): - server = helper_servers.get_server_data_by_id(self.server_id) + server = HelperServers.get_server_data_by_id(self.server_id) logger.info(f"Getting players for server {server}") @@ -1287,7 +1287,7 @@ class Server: server_port = server["server_port"] logger.debug(f"Pinging {internal_ip} on port {server_port}") - if helper_servers.get_server_type_by_id(self.server_id) != "minecraft-bedrock": + if HelperServers.get_server_type_by_id(self.server_id) != "minecraft-bedrock": int_mc_ping = ping(internal_ip, int(server_port)) ping_data = {} @@ -1301,7 +1301,7 @@ class Server: def get_raw_server_stats(self, server_id): try: - server = helper_servers.get_server_obj(server_id) + server = HelperServers.get_server_obj(server_id) except: return { "id": server_id, @@ -1323,10 +1323,10 @@ class Server: } server_stats = {} - server = helper_servers.get_server_obj(server_id) + server = HelperServers.get_server_obj(server_id) if not server: return {} - server_dt = helper_servers.get_server_data_by_id(server_id) + server_dt = HelperServers.get_server_data_by_id(server_id) logger.debug(f"Getting stats for server: {server_id}") @@ -1347,7 +1347,7 @@ class Server: server_port = server_dt["server_port"] logger.debug(f"Pinging server '{self.name}' on {internal_ip}:{server_port}") - if helper_servers.get_server_type_by_id(server_id) == "minecraft-bedrock": + if HelperServers.get_server_type_by_id(server_id) == "minecraft-bedrock": int_mc_ping = ping_bedrock(internal_ip, int(server_port)) else: int_mc_ping = ping(internal_ip, int(server_port)) @@ -1358,7 +1358,7 @@ class Server: # otherwise people have gotten confused. if self.check_running(): # if we got a good ping return, let's parse it - if helper_servers.get_server_type_by_id(server_id) != "minecraft-bedrock": + if HelperServers.get_server_type_by_id(server_id) != "minecraft-bedrock": if int_mc_ping: int_data = True ping_data = Stats.parse_server_ping(int_mc_ping) @@ -1385,7 +1385,7 @@ class Server: else: if int_mc_ping: int_data = True - ping_data = Stats.parse_server_RakNet_ping(int_mc_ping) + ping_data = Stats.parse_server_raknet_ping(int_mc_ping) try: server_icon = base64.encodebytes(ping_data["icon"]) except Exception as ex: @@ -1453,23 +1453,23 @@ class Server: def record_server_stats(self): server = self.get_servers_stats() - Server_Stats.insert( + ServerStats.insert( { - Server_Stats.server_id: server.get("id", 0), - Server_Stats.started: server.get("started", ""), - Server_Stats.running: server.get("running", False), - Server_Stats.cpu: server.get("cpu", 0), - Server_Stats.mem: server.get("mem", 0), - Server_Stats.mem_percent: server.get("mem_percent", 0), - Server_Stats.world_name: server.get("world_name", ""), - Server_Stats.world_size: server.get("world_size", ""), - Server_Stats.server_port: server.get("server_port", ""), - Server_Stats.int_ping_results: server.get("int_ping_results", False), - Server_Stats.online: server.get("online", False), - Server_Stats.max: server.get("max", False), - Server_Stats.players: server.get("players", False), - Server_Stats.desc: server.get("desc", False), - Server_Stats.version: server.get("version", False), + ServerStats.server_id: server.get("id", 0), + ServerStats.started: server.get("started", ""), + ServerStats.running: server.get("running", False), + ServerStats.cpu: server.get("cpu", 0), + ServerStats.mem: server.get("mem", 0), + ServerStats.mem_percent: server.get("mem_percent", 0), + ServerStats.world_name: server.get("world_name", ""), + ServerStats.world_size: server.get("world_size", ""), + ServerStats.server_port: server.get("server_port", ""), + ServerStats.int_ping_results: server.get("int_ping_results", False), + ServerStats.online: server.get("online", False), + ServerStats.max: server.get("max", False), + ServerStats.players: server.get("players", False), + ServerStats.desc: server.get("desc", False), + ServerStats.version: server.get("version", False), } ).execute() @@ -1478,4 +1478,4 @@ class Server: now = datetime.datetime.now() last_week = now.day - max_age - Server_Stats.delete().where(Server_Stats.created < last_week).execute() + ServerStats.delete().where(ServerStats.created < last_week).execute() diff --git a/app/classes/shared/tasks.py b/app/classes/shared/tasks.py index 60272f14..93f53a25 100644 --- a/app/classes/shared/tasks.py +++ b/app/classes/shared/tasks.py @@ -9,8 +9,8 @@ from apscheduler.events import EVENT_JOB_EXECUTED from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.triggers.cron import CronTrigger -from app.classes.models.management import helpers_management -from app.classes.models.users import helper_users +from app.classes.models.management import HelpersManagement +from app.classes.models.users import HelperUsers from app.classes.shared.console import Console from app.classes.web.tornado_handler import Webserver @@ -70,7 +70,7 @@ class TasksManager: return self.main_thread_exiting def reload_schedule_from_db(self): - jobs = helpers_management.get_schedules_enabled() + jobs = HelpersManagement.get_schedules_enabled() logger.info("Reload from DB called. Current enabled schedules: ") for item in jobs: logger.info(f"JOB: {item}") @@ -78,19 +78,19 @@ class TasksManager: def command_watcher(self): while True: # select any commands waiting to be processed - commands = helpers_management.get_unactioned_commands() - for c in commands: + commands = HelpersManagement.get_unactioned_commands() + for cmd in commands: try: - svr = self.controller.get_server_obj(c.server_id) + svr = self.controller.get_server_obj(cmd.server_id) except: logger.error( "Server value requested does note exist! " "Purging item from waiting commands." ) - helpers_management.mark_command_complete(c.command_id) + HelpersManagement.mark_command_complete(cmd.command_id) - user_id = c.user_id - command = c.command + user_id = cmd.user_id + command = cmd.command if command == "start_server": svr.run_threaded_server(user_id) @@ -108,7 +108,7 @@ class TasksManager: svr.jar_update() else: svr.send_command(command) - helpers_management.mark_command_complete(c.command_id) + HelpersManagement.mark_command_complete(cmd.command_id) time.sleep(1) @@ -153,7 +153,7 @@ class TasksManager: self.realtime_thread.start() def scheduler_thread(self): - schedules = helpers_management.get_schedules_enabled() + schedules = HelpersManagement.get_schedules_enabled() self.scheduler.add_listener(self.schedule_watcher, mask=EVENT_JOB_EXECUTED) # self.scheduler.add_job( # self.scheduler.print_jobs, "interval", seconds=10, id="-1" @@ -165,7 +165,7 @@ class TasksManager: if schedule.cron_string != "": try: self.scheduler.add_job( - helpers_management.add_command, + HelpersManagement.add_command, CronTrigger.from_crontab( schedule.cron_string, timezone=str(self.tz) ), @@ -189,7 +189,7 @@ class TasksManager: else: if schedule.interval_type == "hours": self.scheduler.add_job( - helpers_management.add_command, + HelpersManagement.add_command, "cron", minute=0, hour="*/" + str(schedule.interval), @@ -203,7 +203,7 @@ class TasksManager: ) elif schedule.interval_type == "minutes": self.scheduler.add_job( - helpers_management.add_command, + HelpersManagement.add_command, "cron", minute="*/" + str(schedule.interval), id=str(schedule.schedule_id), @@ -217,7 +217,7 @@ class TasksManager: elif schedule.interval_type == "days": curr_time = schedule.start_time.split(":") self.scheduler.add_job( - helpers_management.add_command, + HelpersManagement.add_command, "cron", day="*/" + str(schedule.interval), hour=curr_time[0], @@ -237,7 +237,7 @@ class TasksManager: logger.info(f"JOB: {item}") def schedule_job(self, job_data): - sch_id = helpers_management.create_scheduled_task( + sch_id = HelpersManagement.create_scheduled_task( job_data["server_id"], job_data["action"], job_data["interval"], @@ -254,13 +254,13 @@ class TasksManager: # Checks to make sure some doofus didn't actually make the newly # created task a child of itself. if str(job_data["parent"]) == str(sch_id): - helpers_management.update_scheduled_task(sch_id, {"parent": None}) + HelpersManagement.update_scheduled_task(sch_id, {"parent": None}) # Check to see if it's enabled and is not a chain reaction. if job_data["enabled"] and job_data["interval_type"] != "reaction": if job_data["cron_string"] != "": try: self.scheduler.add_job( - helpers_management.add_command, + HelpersManagement.add_command, CronTrigger.from_crontab( job_data["cron_string"], timezone=str(self.tz) ), @@ -282,7 +282,7 @@ class TasksManager: else: if job_data["interval_type"] == "hours": self.scheduler.add_job( - helpers_management.add_command, + HelpersManagement.add_command, "cron", minute=0, hour="*/" + str(job_data["interval"]), @@ -296,7 +296,7 @@ class TasksManager: ) elif job_data["interval_type"] == "minutes": self.scheduler.add_job( - helpers_management.add_command, + HelpersManagement.add_command, "cron", minute="*/" + str(job_data["interval"]), id=str(sch_id), @@ -310,7 +310,7 @@ class TasksManager: elif job_data["interval_type"] == "days": curr_time = job_data["start_time"].split(":") self.scheduler.add_job( - helpers_management.add_command, + HelpersManagement.add_command, "cron", day="*/" + str(job_data["interval"]), hour=curr_time[0], @@ -329,14 +329,14 @@ class TasksManager: logger.info(f"JOB: {item}") def remove_all_server_tasks(self, server_id): - schedules = helpers_management.get_schedules_by_server(server_id) + schedules = HelpersManagement.get_schedules_by_server(server_id) for schedule in schedules: if schedule.interval != "reaction": self.remove_job(schedule.schedule_id) def remove_job(self, sch_id): - job = helpers_management.get_scheduled_task_model(sch_id) - for schedule in helpers_management.get_child_schedules(sch_id): + job = HelpersManagement.get_scheduled_task_model(sch_id) + for schedule in HelpersManagement.get_child_schedules(sch_id): self.controller.management_helper.update_scheduled_task( schedule.schedule_id, {"parent": None} ) @@ -352,11 +352,11 @@ class TasksManager: ) def update_job(self, sch_id, job_data): - helpers_management.update_scheduled_task(sch_id, job_data) + HelpersManagement.update_scheduled_task(sch_id, job_data) # Checks to make sure some doofus didn't actually make the newly # created task a child of itself. if str(job_data["parent"]) == str(sch_id): - helpers_management.update_scheduled_task(sch_id, {"parent": None}) + HelpersManagement.update_scheduled_task(sch_id, {"parent": None}) try: if job_data["interval"] != "reaction": self.scheduler.remove_job(str(sch_id)) @@ -371,7 +371,7 @@ class TasksManager: if job_data["cron_string"] != "": try: self.scheduler.add_job( - helpers_management.add_command, + HelpersManagement.add_command, CronTrigger.from_crontab( job_data["cron_string"], timezone=str(self.tz) ), @@ -390,7 +390,7 @@ class TasksManager: else: if job_data["interval_type"] == "hours": self.scheduler.add_job( - helpers_management.add_command, + HelpersManagement.add_command, "cron", minute=0, hour="*/" + str(job_data["interval"]), @@ -404,7 +404,7 @@ class TasksManager: ) elif job_data["interval_type"] == "minutes": self.scheduler.add_job( - helpers_management.add_command, + HelpersManagement.add_command, "cron", minute="*/" + str(job_data["interval"]), id=str(sch_id), @@ -418,7 +418,7 @@ class TasksManager: elif job_data["interval_type"] == "days": curr_time = job_data["start_time"].split(":") self.scheduler.add_job( - helpers_management.add_command, + HelpersManagement.add_command, "cron", day="*/" + str(job_data["interval"]), hour=curr_time[0], @@ -449,7 +449,7 @@ class TasksManager: ) self.controller.management.add_to_audit_log_raw( "system", - helper_users.get_user_id_by_name("system"), + HelperUsers.get_user_id_by_name("system"), task.server_id, f"Task with id {task.schedule_id} completed successfully", "127.0.0.1", @@ -461,7 +461,7 @@ class TasksManager: # check for any child tasks for this. It's kind of backward, # but this makes DB management a lot easier. One to one # instead of one to many. - for schedule in helpers_management.get_child_schedules_by_server( + for schedule in HelpersManagement.get_child_schedules_by_server( task.schedule_id, task.server_id ): # event job ID's are strings so we need to look at @@ -472,7 +472,7 @@ class TasksManager: seconds=schedule.delay ) self.scheduler.add_job( - helpers_management.add_command, + HelpersManagement.add_command, "date", run_date=delaytime, id=str(schedule.schedule_id), @@ -526,22 +526,22 @@ class TasksManager: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) - host_stats = helpers_management.get_latest_hosts_stats() + host_stats = HelpersManagement.get_latest_hosts_stats() while True: if host_stats.get( "cpu_usage" - ) != helpers_management.get_latest_hosts_stats().get( + ) != HelpersManagement.get_latest_hosts_stats().get( "cpu_usage" ) or host_stats.get( "mem_percent" - ) != helpers_management.get_latest_hosts_stats().get( + ) != HelpersManagement.get_latest_hosts_stats().get( "mem_percent" ): # Stats are different - host_stats = helpers_management.get_latest_hosts_stats() + host_stats = HelpersManagement.get_latest_hosts_stats() if len(self.helper.websocket_helper.clients) > 0: # There are clients self.helper.websocket_helper.broadcast_page( diff --git a/app/classes/web/ajax_handler.py b/app/classes/web/ajax_handler.py index 49eeec9e..98c599bc 100644 --- a/app/classes/web/ajax_handler.py +++ b/app/classes/web/ajax_handler.py @@ -7,7 +7,7 @@ import bleach import tornado.web import tornado.escape -from app.classes.models.server_permissions import Enum_Permissions_Server +from app.classes.models.server_permissions import EnumPermissionsServer from app.classes.shared.console import Console from app.classes.shared.helpers import Helpers from app.classes.shared.server import ServerOutBuf @@ -68,11 +68,13 @@ class AjaxHandler(BaseHandler): else: data = ServerOutBuf.lines.get(server_id, []) - for d in data: + for line in data: try: - d = re.sub("(\033\\[(0;)?[0-9]*[A-z]?(;[0-9])?m?)|(> )", "", d) - d = re.sub("[A-z]{2}\b\b", "", d) - line = self.helper.log_colors(html.escape(d)) + line = re.sub( + "(\033\\[(0;)?[0-9]*[A-z]?(;[0-9])?m?)|(> )", "", line + ) + line = re.sub("[A-z]{2}\b\b", "", line) + line = self.helper.log_colors(html.escape(line)) self.write(f"{line}
    ") # self.write(d.encode("utf-8")) @@ -265,14 +267,14 @@ class AjaxHandler(BaseHandler): server_id = self.get_argument("id", None) permissions = { - "Commands": Enum_Permissions_Server.Commands, - "Terminal": Enum_Permissions_Server.Terminal, - "Logs": Enum_Permissions_Server.Logs, - "Schedule": Enum_Permissions_Server.Schedule, - "Backup": Enum_Permissions_Server.Backup, - "Files": Enum_Permissions_Server.Files, - "Config": Enum_Permissions_Server.Config, - "Players": Enum_Permissions_Server.Players, + "Commands": EnumPermissionsServer.COMMANDS, + "Terminal": EnumPermissionsServer.TERMINAL, + "Logs": EnumPermissionsServer.LOGS, + "Schedule": EnumPermissionsServer.SCHEDULE, + "Backup": EnumPermissionsServer.BACKUP, + "Files": EnumPermissionsServer.FILES, + "Config": EnumPermissionsServer.CONFIG, + "Players": EnumPermissionsServer.PLAYERS, } user_perms = self.controller.server_perms.get_user_id_permissions_list( exec_user["user_id"], server_id @@ -384,10 +386,10 @@ class AjaxHandler(BaseHandler): if server_data["type"] == "minecraft-java": backup_path = svr_obj.backup_path if Helpers.validate_traversal(backup_path, zip_name): - tempDir = Helpers.unzip_backup_archive(backup_path, zip_name) + temp_dir = Helpers.unzip_backup_archive(backup_path, zip_name) new_server = self.controller.import_zip_server( svr_obj.server_name, - tempDir, + temp_dir, server_data["executable"], "1", "2", @@ -404,10 +406,10 @@ class AjaxHandler(BaseHandler): else: backup_path = svr_obj.backup_path if Helpers.validate_traversal(backup_path, zip_name): - tempDir = Helpers.unzip_backup_archive(backup_path, zip_name) + temp_dir = Helpers.unzip_backup_archive(backup_path, zip_name) new_server = self.controller.import_bedrock_zip_server( svr_obj.server_name, - tempDir, + temp_dir, server_data["executable"], server_data["server_port"], ) @@ -454,14 +456,14 @@ class AjaxHandler(BaseHandler): server_id = self.get_argument("id", None) permissions = { - "Commands": Enum_Permissions_Server.Commands, - "Terminal": Enum_Permissions_Server.Terminal, - "Logs": Enum_Permissions_Server.Logs, - "Schedule": Enum_Permissions_Server.Schedule, - "Backup": Enum_Permissions_Server.Backup, - "Files": Enum_Permissions_Server.Files, - "Config": Enum_Permissions_Server.Config, - "Players": Enum_Permissions_Server.Players, + "Commands": EnumPermissionsServer.COMMANDS, + "Terminal": EnumPermissionsServer.TERMINAL, + "Logs": EnumPermissionsServer.LOGS, + "Schedule": EnumPermissionsServer.SCHEDULE, + "Backup": EnumPermissionsServer.BACKUP, + "Files": EnumPermissionsServer.FILES, + "Config": EnumPermissionsServer.CONFIG, + "Players": EnumPermissionsServer.PLAYERS, } user_perms = self.controller.server_perms.get_user_id_permissions_list( exec_user["user_id"], server_id @@ -581,3 +583,6 @@ class AjaxHandler(BaseHandler): ) return return True + + +0 diff --git a/app/classes/web/api_handler.py b/app/classes/web/api_handler.py index b0736da5..877ba6ba 100644 --- a/app/classes/web/api_handler.py +++ b/app/classes/web/api_handler.py @@ -2,8 +2,8 @@ from datetime import datetime import logging import re -from app.classes.controllers.crafty_perms_controller import Enum_Permissions_Crafty -from app.classes.controllers.server_perms_controller import Enum_Permissions_Server +from app.classes.controllers.crafty_perms_controller import EnumPermissionsCrafty +from app.classes.controllers.server_perms_controller import EnumPermissionsServer from app.classes.web.base_handler import BaseHandler logger = logging.getLogger(__name__) @@ -42,17 +42,17 @@ class ApiHandler(BaseHandler): def authenticate_user(self) -> bool: self.permissions = { - "Commands": Enum_Permissions_Server.Commands, - "Terminal": Enum_Permissions_Server.Terminal, - "Logs": Enum_Permissions_Server.Logs, - "Schedule": Enum_Permissions_Server.Schedule, - "Backup": Enum_Permissions_Server.Backup, - "Files": Enum_Permissions_Server.Files, - "Config": Enum_Permissions_Server.Config, - "Players": Enum_Permissions_Server.Players, - "Server_Creation": Enum_Permissions_Crafty.Server_Creation, - "User_Config": Enum_Permissions_Crafty.User_Config, - "Roles_Config": Enum_Permissions_Crafty.Roles_Config, + "Commands": EnumPermissionsServer.COMMANDS, + "Terminal": EnumPermissionsServer.TERMINAL, + "Logs": EnumPermissionsServer.LOGS, + "Schedule": EnumPermissionsServer.SCHEDULE, + "Backup": EnumPermissionsServer.BACKUP, + "Files": EnumPermissionsServer.FILES, + "Config": EnumPermissionsServer.CONFIG, + "Players": EnumPermissionsServer.PLAYERS, + "Server_Creation": EnumPermissionsCrafty.SERVER_CREATION, + "User_Config": EnumPermissionsCrafty.USER_CONFIG, + "Roles_Config": EnumPermissionsCrafty.ROLES_CONFIG, } try: logger.debug("Searching for specified token") diff --git a/app/classes/web/default_handler.py b/app/classes/web/default_handler.py index 8c417d21..c0bbc9ad 100644 --- a/app/classes/web/default_handler.py +++ b/app/classes/web/default_handler.py @@ -8,8 +8,7 @@ logger = logging.getLogger(__name__) class DefaultHandler(BaseHandler): # Override prepare() instead of get() to cover all possible HTTP methods. - # pylint: disable=arguments-differ - def prepare(self, page=None): + def prepare(self, page=None): # pylint: disable=arguments-differ if page is not None: self.set_status(404) self.render( diff --git a/app/classes/web/file_handler.py b/app/classes/web/file_handler.py index 63c7d57a..bac3b02c 100644 --- a/app/classes/web/file_handler.py +++ b/app/classes/web/file_handler.py @@ -4,7 +4,7 @@ import bleach import tornado.web import tornado.escape -from app.classes.models.server_permissions import Enum_Permissions_Server +from app.classes.models.server_permissions import EnumPermissionsServer from app.classes.shared.console import Console from app.classes.shared.helpers import Helpers from app.classes.shared.file_helpers import FileHelpers @@ -31,14 +31,14 @@ class FileHandler(BaseHandler): server_id = self.get_argument("id", None) permissions = { - "Commands": Enum_Permissions_Server.Commands, - "Terminal": Enum_Permissions_Server.Terminal, - "Logs": Enum_Permissions_Server.Logs, - "Schedule": Enum_Permissions_Server.Schedule, - "Backup": Enum_Permissions_Server.Backup, - "Files": Enum_Permissions_Server.Files, - "Config": Enum_Permissions_Server.Config, - "Players": Enum_Permissions_Server.Players, + "Commands": EnumPermissionsServer.COMMANDS, + "Terminal": EnumPermissionsServer.TERMINAL, + "Logs": EnumPermissionsServer.LOGS, + "Schedule": EnumPermissionsServer.SCHEDULE, + "Backup": EnumPermissionsServer.BACKUP, + "Files": EnumPermissionsServer.FILES, + "Config": EnumPermissionsServer.CONFIG, + "Players": EnumPermissionsServer.PLAYERS, } user_perms = self.controller.server_perms.get_user_id_permissions_list( exec_user["user_id"], server_id @@ -138,14 +138,14 @@ class FileHandler(BaseHandler): server_id = self.get_argument("id", None) permissions = { - "Commands": Enum_Permissions_Server.Commands, - "Terminal": Enum_Permissions_Server.Terminal, - "Logs": Enum_Permissions_Server.Logs, - "Schedule": Enum_Permissions_Server.Schedule, - "Backup": Enum_Permissions_Server.Backup, - "Files": Enum_Permissions_Server.Files, - "Config": Enum_Permissions_Server.Config, - "Players": Enum_Permissions_Server.Players, + "Commands": EnumPermissionsServer.COMMANDS, + "Terminal": EnumPermissionsServer.TERMINAL, + "Logs": EnumPermissionsServer.LOGS, + "Schedule": EnumPermissionsServer.SCHEDULE, + "Backup": EnumPermissionsServer.BACKUP, + "Files": EnumPermissionsServer.FILES, + "Config": EnumPermissionsServer.CONFIG, + "Players": EnumPermissionsServer.PLAYERS, } user_perms = self.controller.server_perms.get_user_id_permissions_list( exec_user["user_id"], server_id @@ -223,7 +223,7 @@ class FileHandler(BaseHandler): self.redirect("/panel/error?error=Unauthorized access to Files") return path = Helpers.get_os_understandable_path(self.get_argument("path", None)) - Helpers.unzipFile(path) + Helpers.unzip_file(path) self.redirect(f"/panel/server_detail?id={server_id}&subpage=files") return @@ -237,14 +237,14 @@ class FileHandler(BaseHandler): server_id = self.get_argument("id", None) permissions = { - "Commands": Enum_Permissions_Server.Commands, - "Terminal": Enum_Permissions_Server.Terminal, - "Logs": Enum_Permissions_Server.Logs, - "Schedule": Enum_Permissions_Server.Schedule, - "Backup": Enum_Permissions_Server.Backup, - "Files": Enum_Permissions_Server.Files, - "Config": Enum_Permissions_Server.Config, - "Players": Enum_Permissions_Server.Players, + "Commands": EnumPermissionsServer.COMMANDS, + "Terminal": EnumPermissionsServer.TERMINAL, + "Logs": EnumPermissionsServer.LOGS, + "Schedule": EnumPermissionsServer.SCHEDULE, + "Backup": EnumPermissionsServer.BACKUP, + "Files": EnumPermissionsServer.FILES, + "Config": EnumPermissionsServer.CONFIG, + "Players": EnumPermissionsServer.PLAYERS, } user_perms = self.controller.server_perms.get_user_id_permissions_list( exec_user["user_id"], server_id @@ -325,14 +325,14 @@ class FileHandler(BaseHandler): server_id = self.get_argument("id", None) permissions = { - "Commands": Enum_Permissions_Server.Commands, - "Terminal": Enum_Permissions_Server.Terminal, - "Logs": Enum_Permissions_Server.Logs, - "Schedule": Enum_Permissions_Server.Schedule, - "Backup": Enum_Permissions_Server.Backup, - "Files": Enum_Permissions_Server.Files, - "Config": Enum_Permissions_Server.Config, - "Players": Enum_Permissions_Server.Players, + "Commands": EnumPermissionsServer.COMMANDS, + "Terminal": EnumPermissionsServer.TERMINAL, + "Logs": EnumPermissionsServer.LOGS, + "Schedule": EnumPermissionsServer.SCHEDULE, + "Backup": EnumPermissionsServer.BACKUP, + "Files": EnumPermissionsServer.FILES, + "Config": EnumPermissionsServer.CONFIG, + "Players": EnumPermissionsServer.PLAYERS, } user_perms = self.controller.server_perms.get_user_id_permissions_list( exec_user["user_id"], server_id @@ -436,14 +436,14 @@ class FileHandler(BaseHandler): server_id = self.get_argument("id", None) permissions = { - "Commands": Enum_Permissions_Server.Commands, - "Terminal": Enum_Permissions_Server.Terminal, - "Logs": Enum_Permissions_Server.Logs, - "Schedule": Enum_Permissions_Server.Schedule, - "Backup": Enum_Permissions_Server.Backup, - "Files": Enum_Permissions_Server.Files, - "Config": Enum_Permissions_Server.Config, - "Players": Enum_Permissions_Server.Players, + "Commands": EnumPermissionsServer.COMMANDS, + "Terminal": EnumPermissionsServer.TERMINAL, + "Logs": EnumPermissionsServer.LOGS, + "Schedule": EnumPermissionsServer.SCHEDULE, + "Backup": EnumPermissionsServer.BACKUP, + "Files": EnumPermissionsServer.FILES, + "Config": EnumPermissionsServer.CONFIG, + "Players": EnumPermissionsServer.PLAYERS, } user_perms = self.controller.server_perms.get_user_id_permissions_list( exec_user["user_id"], server_id diff --git a/app/classes/web/panel_handler.py b/app/classes/web/panel_handler.py index 8e877652..5c61d3ac 100644 --- a/app/classes/web/panel_handler.py +++ b/app/classes/web/panel_handler.py @@ -17,9 +17,9 @@ from tornado import iostream from tzlocal import get_localzone from cron_validator import CronValidator -from app.classes.models.server_permissions import Enum_Permissions_Server -from app.classes.models.crafty_permissions import Enum_Permissions_Crafty -from app.classes.models.management import helpers_management +from app.classes.models.server_permissions import EnumPermissionsServer +from app.classes.models.crafty_permissions import EnumPermissionsCrafty +from app.classes.models.management import HelpersManagement from app.classes.shared.helpers import Helpers from app.classes.web.base_handler import BaseHandler @@ -185,10 +185,10 @@ class PanelHandler(BaseHandler): ) page_data["num_players"] = total_players - for s in page_data["servers"]: + for server in page_data["servers"]: try: - data = json.loads(s["int_ping_results"]) - s["int_ping_results"] = data + data = json.loads(server["int_ping_results"]) + server["int_ping_results"] = data except Exception as e: logger.error(f"Failed server data for page with error: {e}") @@ -267,9 +267,9 @@ class PanelHandler(BaseHandler): "user_role": exec_user_role, "user_crafty_permissions": exec_user_crafty_permissions, "crafty_permissions": { - "Server_Creation": Enum_Permissions_Crafty.Server_Creation, - "User_Config": Enum_Permissions_Crafty.User_Config, - "Roles_Config": Enum_Permissions_Crafty.Roles_Config, + "Server_Creation": EnumPermissionsCrafty.SERVER_CREATION, + "User_Config": EnumPermissionsCrafty.USER_CONFIG, + "Roles_Config": EnumPermissionsCrafty.ROLES_CONFIG, }, "server_stats": { "total": len(defined_servers), @@ -285,7 +285,7 @@ class PanelHandler(BaseHandler): "error": error, "time": formatted_time, "lang": self.controller.users.get_user_lang_by_id(exec_user["user_id"]), - "lang_page": Helpers.getLangPage( + "lang_page": Helpers.get_lang_page( self.controller.users.get_user_lang_by_id(exec_user["user_id"]) ), "super_user": superuser, @@ -307,8 +307,10 @@ class PanelHandler(BaseHandler): # Get grvatar hash for profile pictures if exec_user["email"] != "default@example.com" or "": - g = libgravatar.Gravatar(libgravatar.sanitize_email(exec_user["email"])) - url = g.get_image( + gravatar = libgravatar.Gravatar( + libgravatar.sanitize_email(exec_user["email"]) + ) + url = gravatar.get_image( size=80, default="404", force_default=False, @@ -498,14 +500,14 @@ class PanelHandler(BaseHandler): ) page_data["active_link"] = subpage page_data["permissions"] = { - "Commands": Enum_Permissions_Server.Commands, - "Terminal": Enum_Permissions_Server.Terminal, - "Logs": Enum_Permissions_Server.Logs, - "Schedule": Enum_Permissions_Server.Schedule, - "Backup": Enum_Permissions_Server.Backup, - "Files": Enum_Permissions_Server.Files, - "Config": Enum_Permissions_Server.Config, - "Players": Enum_Permissions_Server.Players, + "Commands": EnumPermissionsServer.COMMANDS, + "Terminal": EnumPermissionsServer.TERMINAL, + "Logs": EnumPermissionsServer.LOGS, + "Schedule": EnumPermissionsServer.SCHEDULE, + "Backup": EnumPermissionsServer.BACKUP, + "Files": EnumPermissionsServer.FILES, + "Config": EnumPermissionsServer.CONFIG, + "Players": EnumPermissionsServer.PLAYERS, } page_data[ "user_permissions" @@ -581,7 +583,7 @@ class PanelHandler(BaseHandler): "/panel/error?error=Unauthorized access To Schedules" ) return - page_data["schedules"] = helpers_management.get_schedules_by_server( + page_data["schedules"] = HelpersManagement.get_schedules_by_server( server_id ) @@ -767,7 +769,7 @@ class PanelHandler(BaseHandler): page_data["user"]["roles"] = set() page_data["user"]["hints"] = True - if Enum_Permissions_Crafty.User_Config not in exec_user_crafty_permissions: + if EnumPermissionsCrafty.USER_CONFIG not in exec_user_crafty_permissions: self.redirect( "/panel/error?error=Unauthorized access: not a user editor" ) @@ -806,7 +808,7 @@ class PanelHandler(BaseHandler): elif page == "add_schedule": server_id = self.get_argument("id", None) - page_data["schedules"] = helpers_management.get_schedules_by_server( + page_data["schedules"] = HelpersManagement.get_schedules_by_server( server_id ) page_data["get_players"] = lambda: self.controller.stats.get_server_players( @@ -814,14 +816,14 @@ class PanelHandler(BaseHandler): ) page_data["active_link"] = "schedules" page_data["permissions"] = { - "Commands": Enum_Permissions_Server.Commands, - "Terminal": Enum_Permissions_Server.Terminal, - "Logs": Enum_Permissions_Server.Logs, - "Schedule": Enum_Permissions_Server.Schedule, - "Backup": Enum_Permissions_Server.Backup, - "Files": Enum_Permissions_Server.Files, - "Config": Enum_Permissions_Server.Config, - "Players": Enum_Permissions_Server.Players, + "Commands": EnumPermissionsServer.COMMANDS, + "Terminal": EnumPermissionsServer.TERMINAL, + "Logs": EnumPermissionsServer.LOGS, + "Schedule": EnumPermissionsServer.SCHEDULE, + "Backup": EnumPermissionsServer.BACKUP, + "Files": EnumPermissionsServer.FILES, + "Config": EnumPermissionsServer.CONFIG, + "Players": EnumPermissionsServer.PLAYERS, } page_data[ "user_permissions" @@ -854,7 +856,7 @@ class PanelHandler(BaseHandler): page_data["schedule"]["difficulty"] = "basic" page_data["schedule"]["interval_type"] = "days" - if not Enum_Permissions_Server.Schedule in page_data["user_permissions"]: + if not EnumPermissionsServer.SCHEDULE in page_data["user_permissions"]: if not superuser: self.redirect("/panel/error?error=Unauthorized access To Schedules") return @@ -863,7 +865,7 @@ class PanelHandler(BaseHandler): elif page == "edit_schedule": server_id = self.get_argument("id", None) - page_data["schedules"] = helpers_management.get_schedules_by_server( + page_data["schedules"] = HelpersManagement.get_schedules_by_server( server_id ) sch_id = self.get_argument("sch_id", None) @@ -873,14 +875,14 @@ class PanelHandler(BaseHandler): ) page_data["active_link"] = "schedules" page_data["permissions"] = { - "Commands": Enum_Permissions_Server.Commands, - "Terminal": Enum_Permissions_Server.Terminal, - "Logs": Enum_Permissions_Server.Logs, - "Schedule": Enum_Permissions_Server.Schedule, - "Backup": Enum_Permissions_Server.Backup, - "Files": Enum_Permissions_Server.Files, - "Config": Enum_Permissions_Server.Config, - "Players": Enum_Permissions_Server.Players, + "Commands": EnumPermissionsServer.COMMANDS, + "Terminal": EnumPermissionsServer.TERMINAL, + "Logs": EnumPermissionsServer.LOGS, + "Schedule": EnumPermissionsServer.SCHEDULE, + "Backup": EnumPermissionsServer.BACKUP, + "Files": EnumPermissionsServer.FILES, + "Config": EnumPermissionsServer.CONFIG, + "Players": EnumPermissionsServer.PLAYERS, } page_data[ "user_permissions" @@ -933,7 +935,7 @@ class PanelHandler(BaseHandler): if sch_id is None or server_id is None: self.redirect("/panel/error?error=Invalid server ID or Schedule ID") - if not Enum_Permissions_Server.Schedule in page_data["user_permissions"]: + if not EnumPermissionsServer.SCHEDULE in page_data["user_permissions"]: if not superuser: self.redirect("/panel/error?error=Unauthorized access To Schedules") return @@ -985,9 +987,7 @@ class PanelHandler(BaseHandler): if user_id is None: self.redirect("/panel/error?error=Invalid User ID") return - elif ( - Enum_Permissions_Crafty.User_Config not in exec_user_crafty_permissions - ): + elif EnumPermissionsCrafty.USER_CONFIG not in exec_user_crafty_permissions: if str(user_id) != str(exec_user["user_id"]): self.redirect( "/panel/error?error=Unauthorized access: not a user editor" @@ -1029,7 +1029,7 @@ class PanelHandler(BaseHandler): if ( not superuser - and Enum_Permissions_Crafty.User_Config + and EnumPermissionsCrafty.USER_CONFIG not in exec_user_crafty_permissions ): self.redirect("/panel/error?error=Unauthorized access: not superuser") @@ -1075,7 +1075,7 @@ class PanelHandler(BaseHandler): page_data["user-roles"] = user_roles page_data["users"] = self.controller.users.get_all_users() - if Enum_Permissions_Crafty.Roles_Config not in exec_user_crafty_permissions: + if EnumPermissionsCrafty.ROLES_CONFIG not in exec_user_crafty_permissions: self.redirect( "/panel/error?error=Unauthorized access: not a role editor" ) @@ -1103,7 +1103,7 @@ class PanelHandler(BaseHandler): page_data["user-roles"] = user_roles page_data["users"] = self.controller.users.get_all_users() - if Enum_Permissions_Crafty.Roles_Config not in exec_user_crafty_permissions: + if EnumPermissionsCrafty.ROLES_CONFIG not in exec_user_crafty_permissions: self.redirect( "/panel/error?error=Unauthorized access: not a role editor" ) @@ -1165,7 +1165,7 @@ class PanelHandler(BaseHandler): self.redirect(f"/panel/server_detail?id={server_id}&subpage=files") elif page == "download_support_package": - tempZipStorage = exec_user["support_logs"] + temp_zip_storage = exec_user["support_logs"] # We'll reset the support path for this user now. self.controller.users.set_support_path(exec_user["user_id"], "") @@ -1174,8 +1174,8 @@ class PanelHandler(BaseHandler): "Content-Disposition", "attachment; filename=" + "support_logs.zip" ) chunk_size = 1024 * 1024 * 4 # 4 MiB - if tempZipStorage != "": - with open(tempZipStorage, "rb") as f: + if temp_zip_storage != "": + with open(temp_zip_storage, "rb") as f: while True: chunk = f.read(chunk_size) if not chunk: @@ -1230,14 +1230,14 @@ class PanelHandler(BaseHandler): server_id = self.get_argument("id", None) permissions = { - "Commands": Enum_Permissions_Server.Commands, - "Terminal": Enum_Permissions_Server.Terminal, - "Logs": Enum_Permissions_Server.Logs, - "Schedule": Enum_Permissions_Server.Schedule, - "Backup": Enum_Permissions_Server.Backup, - "Files": Enum_Permissions_Server.Files, - "Config": Enum_Permissions_Server.Config, - "Players": Enum_Permissions_Server.Players, + "Commands": EnumPermissionsServer.COMMANDS, + "Terminal": EnumPermissionsServer.TERMINAL, + "Logs": EnumPermissionsServer.LOGS, + "Schedule": EnumPermissionsServer.SCHEDULE, + "Backup": EnumPermissionsServer.BACKUP, + "Files": EnumPermissionsServer.FILES, + "Config": EnumPermissionsServer.CONFIG, + "Players": EnumPermissionsServer.PLAYERS, } exec_user_role = set() if superuser: @@ -1758,7 +1758,7 @@ class PanelHandler(BaseHandler): superuser = False if not exec_user["superuser"]: if ( - Enum_Permissions_Crafty.User_Config + EnumPermissionsCrafty.USER_CONFIG not in exec_user_crafty_permissions ): if str(user_id) != str(exec_user["user_id"]): @@ -1926,7 +1926,7 @@ class PanelHandler(BaseHandler): else: new_superuser = False - if Enum_Permissions_Crafty.User_Config not in exec_user_crafty_permissions: + if EnumPermissionsCrafty.USER_CONFIG not in exec_user_crafty_permissions: self.redirect( "/panel/error?error=Unauthorized access: not a user editor" ) @@ -1981,7 +1981,7 @@ class PanelHandler(BaseHandler): role_id = bleach.clean(self.get_argument("id", None)) role_name = bleach.clean(self.get_argument("role_name", None)) - if Enum_Permissions_Crafty.Roles_Config not in exec_user_crafty_permissions: + if EnumPermissionsCrafty.ROLES_CONFIG not in exec_user_crafty_permissions: self.redirect( "/panel/error?error=Unauthorized access: not a role editor" ) @@ -2017,7 +2017,7 @@ class PanelHandler(BaseHandler): elif page == "add_role": role_name = bleach.clean(self.get_argument("role_name", None)) - if Enum_Permissions_Crafty.Roles_Config not in exec_user_crafty_permissions: + if EnumPermissionsCrafty.ROLES_CONFIG not in exec_user_crafty_permissions: self.redirect( "/panel/error?error=Unauthorized access: not a role editor" ) @@ -2057,7 +2057,7 @@ class PanelHandler(BaseHandler): self.set_status(404) page_data = { "lang": self.helper.get_setting("language"), - "lang_page": Helpers.getLangPage(self.helper.get_setting("language")), + "lang_page": Helpers.get_lang_page(self.helper.get_setting("language")), } self.render( "public/404.html", translate=self.translator.translate, data=page_data @@ -2078,7 +2078,7 @@ class PanelHandler(BaseHandler): "hosts_data": self.controller.management.get_latest_hosts_stats(), "show_contribute": self.helper.get_setting("show_contribute_link", True), "lang": self.controller.users.get_user_lang_by_id(exec_user["user_id"]), - "lang_page": Helpers.getLangPage( + "lang_page": Helpers.get_lang_page( self.controller.users.get_user_lang_by_id(exec_user["user_id"]) ), } diff --git a/app/classes/web/public_handler.py b/app/classes/web/public_handler.py index 5269ba2e..87db887b 100644 --- a/app/classes/web/public_handler.py +++ b/app/classes/web/public_handler.py @@ -2,7 +2,7 @@ import logging import bleach from app.classes.shared.helpers import Helpers -from app.classes.models.users import helper_users +from app.classes.models.users import HelperUsers from app.classes.web.base_handler import BaseHandler logger = logging.getLogger(__name__) @@ -103,8 +103,8 @@ class PublicHandler(BaseHandler): # pylint: disable=no-member try: - user_id = helper_users.get_user_id_by_name(entered_username.lower()) - user_data = helper_users.get_user_model(user_id) + user_id = HelperUsers.get_user_id_by_name(entered_username.lower()) + user_data = HelperUsers.get_user_model(user_id) except: error_msg = "Incorrect username or password. Please try again." # self.clear_cookie("user") diff --git a/app/classes/web/server_handler.py b/app/classes/web/server_handler.py index 1482200b..44da81df 100644 --- a/app/classes/web/server_handler.py +++ b/app/classes/web/server_handler.py @@ -7,7 +7,7 @@ import bleach import libgravatar import requests -from app.classes.models.crafty_permissions import Enum_Permissions_Crafty +from app.classes.models.crafty_permissions import EnumPermissionsCrafty from app.classes.shared.helpers import Helpers from app.classes.shared.file_helpers import FileHelpers from app.classes.web.base_handler import BaseHandler @@ -18,8 +18,11 @@ logger = logging.getLogger(__name__) class ServerHandler(BaseHandler): @tornado.web.authenticated def get(self, page): - # pylint: disable=unused-variable - api_key, token_data, exec_user = self.current_user + ( + api_key, + _token_data, + exec_user, + ) = self.current_user superuser = exec_user["superuser"] if api_key is not None: superuser = superuser and api_key.superuser @@ -58,9 +61,9 @@ class ServerHandler(BaseHandler): "roles": list_roles, "user_crafty_permissions": exec_user_crafty_permissions, "crafty_permissions": { - "Server_Creation": Enum_Permissions_Crafty.Server_Creation, - "User_Config": Enum_Permissions_Crafty.User_Config, - "Roles_Config": Enum_Permissions_Crafty.Roles_Config, + "Server_Creation": EnumPermissionsCrafty.SERVER_CREATION, + "User_Config": EnumPermissionsCrafty.USER_CONFIG, + "Roles_Config": EnumPermissionsCrafty.ROLES_CONFIG, }, "server_stats": { "total": len(self.controller.list_defined_servers()), @@ -74,7 +77,7 @@ class ServerHandler(BaseHandler): "menu_servers": defined_servers, "show_contribute": self.helper.get_setting("show_contribute_link", True), "lang": self.controller.users.get_user_lang_by_id(exec_user["user_id"]), - "lang_page": Helpers.getLangPage( + "lang_page": Helpers.get_lang_page( self.controller.users.get_user_lang_by_id(exec_user["user_id"]) ), "api_key": { @@ -95,8 +98,10 @@ class ServerHandler(BaseHandler): rating = "g" if exec_user["email"] != "default@example.com" or "": - g = libgravatar.Gravatar(libgravatar.sanitize_email(exec_user["email"])) - url = g.get_image( + gravatar = libgravatar.Gravatar( + libgravatar.sanitize_email(exec_user["email"]) + ) + url = gravatar.get_image( size=80, default="404", force_default=False, @@ -155,8 +160,7 @@ class ServerHandler(BaseHandler): @tornado.web.authenticated def post(self, page): - # pylint: disable=unused-variable - api_key, token_data, exec_user = self.current_user + api_key, _token_data, exec_user = self.current_user superuser = exec_user["superuser"] if api_key is not None: superuser = superuser and api_key.superuser @@ -167,7 +171,7 @@ class ServerHandler(BaseHandler): "user_data": exec_user, "show_contribute": self.helper.get_setting("show_contribute_link", True), "lang": self.controller.users.get_user_lang_by_id(exec_user["user_id"]), - "lang_page": Helpers.getLangPage( + "lang_page": Helpers.get_lang_page( self.controller.users.get_user_lang_by_id(exec_user["user_id"]) ), } @@ -327,7 +331,6 @@ class ServerHandler(BaseHandler): server_type, server_version = server_parts # TODO: add server type check here and call the correct server # add functions if not a jar - role_ids = self.controller.users.get_user_roles_id(exec_user["user_id"]) new_server_id = self.controller.create_jar_server( server_type, server_version, server_name, min_mem, max_mem, port ) @@ -445,7 +448,6 @@ class ServerHandler(BaseHandler): server_type, server_version = server_parts # TODO: add server type check here and call the correct server # add functions if not a jar - role_ids = self.controller.users.get_user_roles_id(exec_user["user_id"]) new_server_id = self.controller.create_jar_server( server_type, server_version, server_name, min_mem, max_mem, port ) diff --git a/app/classes/web/tornado_handler.py b/app/classes/web/tornado_handler.py index b0b1a3b0..9ebcd5f7 100644 --- a/app/classes/web/tornado_handler.py +++ b/app/classes/web/tornado_handler.py @@ -44,8 +44,8 @@ logger = logging.getLogger(__name__) class Webserver: def __init__(self, helper, controller, tasks_manager): self.ioloop = None - self.HTTP_Server = None - self.HTTPS_Server = None + self.http_server = None + self.https_server = None self.helper = helper self.controller = controller self.tasks_manager = tasks_manager @@ -177,7 +177,7 @@ class Webserver: static_handler_class=CustomStaticHandler, serve_traceback=debug_errors, ) - HTTPhanders = [ + http_handers = [ (r"/", HTTPHandler, handler_args), (r"/public/(.*)", HTTPHandlerPage, handler_args), (r"/panel/(.*)", HTTPHandlerPage, handler_args), @@ -188,8 +188,8 @@ class Webserver: (r"/ws", HTTPHandlerPage, handler_args), (r"/upload", HTTPHandlerPage, handler_args), ] - HTTPapp = tornado.web.Application( - HTTPhanders, + http_app = tornado.web.Application( + http_handers, template_path=os.path.join(self.helper.webroot, "templates"), static_path=os.path.join(self.helper.webroot, "static"), debug=debug_errors, @@ -202,11 +202,11 @@ class Webserver: serve_traceback=debug_errors, ) - self.HTTP_Server = tornado.httpserver.HTTPServer(HTTPapp) - self.HTTP_Server.listen(http_port) + self.http_server = tornado.httpserver.HTTPServer(http_app) + self.http_server.listen(http_port) - self.HTTPS_Server = tornado.httpserver.HTTPServer(app, ssl_options=cert_objects) - self.HTTPS_Server.listen(https_port) + self.https_server = tornado.httpserver.HTTPServer(app, ssl_options=cert_objects) + self.https_server.listen(https_port) logger.info( f"https://{Helpers.get_local_ip()}:{https_port} " @@ -226,7 +226,7 @@ class Webserver: logger.info("Shutting Down Web Server") Console.info("Shutting Down Web Server") self.ioloop.stop() - self.HTTP_Server.stop() - self.HTTPS_Server.stop() + self.http_server.stop() + self.https_server.stop() logger.info("Web Server Stopped") Console.info("Web Server Stopped") diff --git a/app/classes/web/upload_handler.py b/app/classes/web/upload_handler.py index 4877d5cc..92892ed1 100644 --- a/app/classes/web/upload_handler.py +++ b/app/classes/web/upload_handler.py @@ -5,7 +5,7 @@ import tornado.web import tornado.options import tornado.httpserver -from app.classes.models.server_permissions import Enum_Permissions_Server +from app.classes.models.server_permissions import EnumPermissionsServer from app.classes.shared.console import Console from app.classes.shared.helpers import Helpers from app.classes.shared.main_controller import Controller @@ -40,10 +40,10 @@ class UploadHandler(BaseHandler): user_id = exec_user["user_id"] stream_size_value = self.helper.get_setting("stream_size_GB") - MAX_STREAMED_SIZE = (1024 * 1024 * 1024) * stream_size_value + max_streamed_size = (1024 * 1024 * 1024) * stream_size_value self.content_len = int(self.request.headers.get("Content-Length")) - if self.content_len > MAX_STREAMED_SIZE: + if self.content_len > max_streamed_size: logger.error( f"User with ID {user_id} attempted to upload a file that" f" exceeded the max body size." @@ -91,7 +91,7 @@ class UploadHandler(BaseHandler): Console.warning("Server ID not found in upload handler call") self.do_upload = False - if Enum_Permissions_Server.Files not in exec_user_server_permissions: + if EnumPermissionsServer.FILES not in exec_user_server_permissions: logger.warning( f"User {user_id} tried to upload a file to " f"{server_id} without permissions!" @@ -137,7 +137,7 @@ class UploadHandler(BaseHandler): logger.error(f"Upload failed with error: {e}") self.do_upload = False # If max_body_size is not set, you cannot upload files > 100MB - self.request.connection.set_max_body_size(MAX_STREAMED_SIZE) + self.request.connection.set_max_body_size(max_streamed_size) def post(self): logger.info("Upload completed") diff --git a/app/classes/web/websocket_helper.py b/app/classes/web/websocket_helper.py index 68044b5f..60eed795 100644 --- a/app/classes/web/websocket_helper.py +++ b/app/classes/web/websocket_helper.py @@ -17,8 +17,9 @@ class WebSocketHelper: def remove_client(self, client): self.clients.remove(client) - # pylint: disable=no-self-use - def send_message(self, client, event_type: str, data): + def send_message( + self, client, event_type: str, data + ): # pylint: disable=no-self-use if client.check_auth(): message = str(json.dumps({"event": event_type, "data": data})) client.write_message_helper(message) diff --git a/main.py b/main.py index ccadb3b6..6a083ef2 100644 --- a/main.py +++ b/main.py @@ -6,13 +6,13 @@ import argparse import logging.config import signal import peewee -from app.classes.models.users import helper_users +from app.classes.models.users import HelperUsers from app.classes.shared.console import Console from app.classes.shared.helpers import Helpers console = Console() helper = Helpers() -if helper.checkRoot(): +if helper.check_root(): Console.critical( "Root detected. Root/Admin access denied. " "Run Crafty again with non-elevated permissions." @@ -23,7 +23,7 @@ if helper.checkRoot(): # pylint: disable=wrong-import-position try: from app.classes.models.base_model import database_proxy - from app.classes.shared.main_models import db_builder + from app.classes.shared.main_models import DatabaseBuilder from app.classes.shared.tasks import TasksManager from app.classes.shared.main_controller import Controller from app.classes.shared.migration import MigrationManager @@ -114,11 +114,11 @@ if __name__ == "__main__": migration_manager.up() # Automatically runs migrations # do our installer stuff - user_helper = helper_users(database, helper) - installer = db_builder(database, helper, user_helper) - fresh_install = installer.is_fresh_install() + user_helper = HelperUsers(database, helper) + installer = DatabaseBuilder(database, helper, user_helper) + FRESH_INSTALL = installer.is_fresh_install() - if fresh_install: + if FRESH_INSTALL: Console.debug("Fresh install detected") Console.warning( f"We have detected a fresh install. Please be sure to forward " From 20141f3cba576e4c92eb94f96f33d254875d8e6d Mon Sep 17 00:00:00 2001 From: Zedifus Date: Thu, 14 Apr 2022 03:19:56 +0100 Subject: [PATCH 3/7] Fix typo at EOF MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit '0' is my Discord P-T-T Toggle 😅 --- app/classes/web/ajax_handler.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/app/classes/web/ajax_handler.py b/app/classes/web/ajax_handler.py index 98c599bc..8bb58712 100644 --- a/app/classes/web/ajax_handler.py +++ b/app/classes/web/ajax_handler.py @@ -583,6 +583,3 @@ class AjaxHandler(BaseHandler): ) return return True - - -0 From b380f09b06c1c125959184f9fa928b91eb10d3bc Mon Sep 17 00:00:00 2001 From: Andrew Date: Thu, 14 Apr 2022 19:34:21 -0400 Subject: [PATCH 4/7] Rename get_lang_page --- app/classes/web/public_handler.py | 4 ++-- app/classes/web/status_handler.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/app/classes/web/public_handler.py b/app/classes/web/public_handler.py index 87db887b..f4455fca 100644 --- a/app/classes/web/public_handler.py +++ b/app/classes/web/public_handler.py @@ -37,7 +37,7 @@ class PublicHandler(BaseHandler): "version": self.helper.get_version_string(), "error": error, "lang": self.helper.get_setting("language"), - "lang_page": self.helper.getLangPage(self.helper.get_setting("language")), + "lang_page": self.helper.get_lang_page(self.helper.get_setting("language")), "query": "", } if self.request.query: @@ -86,7 +86,7 @@ class PublicHandler(BaseHandler): "version": self.helper.get_version_string(), "error": error, "lang": self.helper.get_setting("language"), - "lang_page": self.helper.getLangPage(self.helper.get_setting("language")), + "lang_page": self.helper.get_lang_page(self.helper.get_setting("language")), "query": "", } if self.request.query: diff --git a/app/classes/web/status_handler.py b/app/classes/web/status_handler.py index 71b29f62..6e73cdcb 100644 --- a/app/classes/web/status_handler.py +++ b/app/classes/web/status_handler.py @@ -9,7 +9,7 @@ class StatusHandler(BaseHandler): def get(self): page_data = {} page_data["lang"] = self.helper.get_setting("language") - page_data["lang_page"] = self.helper.getLangPage( + page_data["lang_page"] = self.helper.get_lang_page( self.helper.get_setting("language") ) page_data["servers"] = self.controller.servers.get_all_servers_stats() From 2dc85e6f27702cbce1df67fca76dbf4b1b34fbc7 Mon Sep 17 00:00:00 2001 From: Andrew Date: Thu, 14 Apr 2022 19:34:30 -0400 Subject: [PATCH 5/7] Add table name for audit_log --- app/classes/models/management.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/app/classes/models/management.py b/app/classes/models/management.py index 7fbfc919..15bbec76 100644 --- a/app/classes/models/management.py +++ b/app/classes/models/management.py @@ -34,6 +34,9 @@ class AuditLog(BaseModel): ) # When auditing global events, use server ID 0 log_msg = TextField(default="") + class Meta: + table_name = "audit_log" + # ********************************************************************************** # Host_Stats Class From 9fcd510be2bcda64ef51cd41bbbcd8ec474ba09a Mon Sep 17 00:00:00 2001 From: Andrew Date: Thu, 14 Apr 2022 19:45:13 -0400 Subject: [PATCH 6/7] Make unzip_server snake case --- app/classes/web/ajax_handler.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/classes/web/ajax_handler.py b/app/classes/web/ajax_handler.py index 8bb58712..ee788e78 100644 --- a/app/classes/web/ajax_handler.py +++ b/app/classes/web/ajax_handler.py @@ -424,7 +424,7 @@ class AjaxHandler(BaseHandler): elif page == "unzip_server": path = self.get_argument("path", None) if Helpers.check_file_exists(path): - self.helper.unzipServer(path, exec_user["user_id"]) + self.helper.unzip_server(path, exec_user["user_id"]) else: user_id = exec_user["user_id"] if user_id: From 704ffc274227a440e7e458fce92f2b67c32f0c06 Mon Sep 17 00:00:00 2001 From: Andrew Date: Thu, 14 Apr 2022 20:03:19 -0400 Subject: [PATCH 7/7] Fix file unzip --- app/classes/shared/helpers.py | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/app/classes/shared/helpers.py b/app/classes/shared/helpers.py index caf6438b..dfacd362 100644 --- a/app/classes/shared/helpers.py +++ b/app/classes/shared/helpers.py @@ -443,13 +443,24 @@ class Helpers: full_root_path = temp_dir for item in os.listdir(full_root_path): - try: - FileHelpers.move_dir( - os.path.join(full_root_path, item), - os.path.join(new_dir, item), - ) - except Exception as ex: - logger.error(f"ERROR IN ZIP IMPORT: {ex}") + print(item) + if os.path.isdir(os.path.join(full_root_path, item)): + print("dir") + try: + FileHelpers.move_dir( + os.path.join(full_root_path, item), + os.path.join(new_dir, item), + ) + except Exception as ex: + logger.error(f"ERROR IN ZIP IMPORT: {ex}") + else: + try: + FileHelpers.move_file( + os.path.join(full_root_path, item), + os.path.join(new_dir, item), + ) + except Exception as ex: + logger.error(f"ERROR IN ZIP IMPORT: {ex}") except Exception as ex: print(ex) else: