Merge branch 'devops/class-var-naming-refactor' into 'dev'

Refactor class and variable names 🧹

See merge request crafty-controller/crafty-4!249
This commit is contained in:
Iain Powrie 2022-04-15 00:21:31 +00:00
commit d2102bbca0
43 changed files with 1535 additions and 1515 deletions

View File

@ -94,7 +94,6 @@ disable=C0330,
fixme, fixme,
import-error, import-error,
inconsistent-return-statements, inconsistent-return-statements,
invalid-name,
locally-disabled, locally-disabled,
logging-format-interpolation, logging-format-interpolation,
logging-fstring-interpolation, logging-fstring-interpolation,
@ -236,10 +235,20 @@ function-naming-style=snake_case
#function-rgx= #function-rgx=
# Good variable names which should always be accepted, separated by a comma. # Good variable names which should always be accepted, separated by a comma.
good-names=i, good-names=e,
ex,
f,
i,
id,
ip,
j, j,
k, k,
ex, p,
r,
rs,
s,
tz,
v,
Run, Run,
_ _

View File

@ -1,37 +1,37 @@
import logging import logging
from app.classes.models.crafty_permissions import ( from app.classes.models.crafty_permissions import (
Permissions_Crafty, PermissionsCrafty,
Enum_Permissions_Crafty, EnumPermissionsCrafty,
) )
from app.classes.models.users import ApiKeys from app.classes.models.users import ApiKeys
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Crafty_Perms_Controller: class CraftyPermsController:
@staticmethod @staticmethod
def list_defined_crafty_permissions(): def list_defined_crafty_permissions():
permissions_list = Permissions_Crafty.get_permissions_list() permissions_list = PermissionsCrafty.get_permissions_list()
return permissions_list return permissions_list
@staticmethod @staticmethod
def get_mask_crafty_permissions(user_id): 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 return permissions_mask
@staticmethod @staticmethod
def set_permission( 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 permission_mask, permission_tested, value
) )
@staticmethod @staticmethod
def can_create_server(user_id): def can_create_server(user_id):
return Permissions_Crafty.can_add_in_crafty( return PermissionsCrafty.can_add_in_crafty(
user_id, Enum_Permissions_Crafty.Server_Creation user_id, EnumPermissionsCrafty.SERVER_CREATION
) )
@staticmethod @staticmethod
@ -52,22 +52,22 @@ class Crafty_Perms_Controller:
@staticmethod @staticmethod
def list_all_crafty_permissions_quantity_limits(): def list_all_crafty_permissions_quantity_limits():
return Permissions_Crafty.get_all_permission_quantity_list() return PermissionsCrafty.get_all_permission_quantity_list()
@staticmethod @staticmethod
def list_crafty_permissions_quantity_limits(user_id): 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 @staticmethod
def get_crafty_permissions_list(user_id): def get_crafty_permissions_list(user_id):
permissions_mask = Permissions_Crafty.get_crafty_permissions_mask(user_id) permissions_mask = PermissionsCrafty.get_crafty_permissions_mask(user_id)
permissions_list = Permissions_Crafty.get_permissions(permissions_mask) permissions_list = PermissionsCrafty.get_permissions(permissions_mask)
return permissions_list return permissions_list
@staticmethod @staticmethod
def add_server_creation(user_id): def add_server_creation(user_id):
return Permissions_Crafty.add_server_creation(user_id) return PermissionsCrafty.add_server_creation(user_id)
@staticmethod @staticmethod
def get_api_key_permissions_list(key: ApiKeys): 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)

View File

@ -1,12 +1,12 @@
import logging import logging
from app.classes.models.management import helpers_management from app.classes.models.management import HelpersManagement
from app.classes.models.servers import helper_servers from app.classes.models.servers import HelperServers
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Management_Controller: class ManagementController:
def __init__(self, management_helper): def __init__(self, management_helper):
self.management_helper = management_helper self.management_helper = management_helper
@ -15,17 +15,17 @@ class Management_Controller:
# ********************************************************************************** # **********************************************************************************
@staticmethod @staticmethod
def get_latest_hosts_stats(): def get_latest_hosts_stats():
return helpers_management.get_latest_hosts_stats() return HelpersManagement.get_latest_hosts_stats()
# ********************************************************************************** # **********************************************************************************
# Commands Methods # Commands Methods
# ********************************************************************************** # **********************************************************************************
@staticmethod @staticmethod
def get_unactioned_commands(): 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): 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 # Example: Admin issued command start_server for server Survival
self.management_helper.add_to_audit_log( self.management_helper.add_to_audit_log(
@ -34,18 +34,18 @@ class Management_Controller:
server_id, server_id,
remote_ip, remote_ip,
) )
helpers_management.add_command(server_id, user_id, remote_ip, command) HelpersManagement.add_command(server_id, user_id, remote_ip, command)
@staticmethod @staticmethod
def mark_command_complete(command_id=None): 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 # Audit_Log Methods
# ********************************************************************************** # **********************************************************************************
@staticmethod @staticmethod
def get_actity_log(): 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): def add_to_audit_log(self, user_id, log_msg, server_id=None, source_ip=None):
return self.management_helper.add_to_audit_log( return self.management_helper.add_to_audit_log(
@ -71,7 +71,7 @@ class Management_Controller:
comment=None, comment=None,
enabled=True, enabled=True,
): ):
return helpers_management.create_scheduled_task( return HelpersManagement.create_scheduled_task(
server_id, server_id,
action, action,
interval, interval,
@ -84,42 +84,42 @@ class Management_Controller:
@staticmethod @staticmethod
def delete_scheduled_task(schedule_id): def delete_scheduled_task(schedule_id):
return helpers_management.delete_scheduled_task(schedule_id) return HelpersManagement.delete_scheduled_task(schedule_id)
@staticmethod @staticmethod
def update_scheduled_task(schedule_id, updates): 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 @staticmethod
def get_scheduled_task(schedule_id): def get_scheduled_task(schedule_id):
return helpers_management.get_scheduled_task(schedule_id) return HelpersManagement.get_scheduled_task(schedule_id)
@staticmethod @staticmethod
def get_scheduled_task_model(schedule_id): 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 @staticmethod
def get_child_schedules(sch_id): def get_child_schedules(sch_id):
return helpers_management.get_child_schedules(sch_id) return HelpersManagement.get_child_schedules(sch_id)
@staticmethod @staticmethod
def get_schedules_by_server(server_id): 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 @staticmethod
def get_schedules_all(): def get_schedules_all():
return helpers_management.get_schedules_all() return HelpersManagement.get_schedules_all()
@staticmethod @staticmethod
def get_schedules_enabled(): def get_schedules_enabled():
return helpers_management.get_schedules_enabled() return HelpersManagement.get_schedules_enabled()
# ********************************************************************************** # **********************************************************************************
# Backups Methods # Backups Methods
# ********************************************************************************** # **********************************************************************************
@staticmethod @staticmethod
def get_backup_config(server_id): 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( def set_backup_config(
self, self,
@ -135,7 +135,7 @@ class Management_Controller:
@staticmethod @staticmethod
def get_excluded_backup_dirs(server_id: int): 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): 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) self.management_helper.add_excluded_backup_dir(server_id, dir_to_add)

View File

@ -1,34 +1,34 @@
import logging import logging
from app.classes.models.roles import helper_roles from app.classes.models.roles import HelperRoles
from app.classes.models.server_permissions import Permissions_Servers from app.classes.models.server_permissions import PermissionsServers
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Roles_Controller: class RolesController:
def __init__(self, users_helper, roles_helper): def __init__(self, users_helper, roles_helper):
self.users_helper = users_helper self.users_helper = users_helper
self.roles_helper = roles_helper self.roles_helper = roles_helper
@staticmethod @staticmethod
def get_all_roles(): def get_all_roles():
return helper_roles.get_all_roles() return HelperRoles.get_all_roles()
@staticmethod @staticmethod
def get_roleid_by_name(role_name): 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 @staticmethod
def get_role(role_id): def get_role(role_id):
return helper_roles.get_role(role_id) return HelperRoles.get_role(role_id)
@staticmethod @staticmethod
def update_role(role_id: str, role_data=None, permissions_mask: str = "00000000"): def update_role(role_id: str, role_data=None, permissions_mask: str = "00000000"):
if role_data is None: if role_data is None:
role_data = {} role_data = {}
base_data = Roles_Controller.get_role_with_servers(role_id) base_data = RolesController.get_role_with_servers(role_id)
up_data = {} up_data = {}
added_servers = set() added_servers = set()
removed_servers = set() removed_servers = set()
@ -45,37 +45,35 @@ class Roles_Controller:
f"role: {role_data} +server:{added_servers} -server{removed_servers}" f"role: {role_data} +server:{added_servers} -server{removed_servers}"
) )
for server in added_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"]: for server in base_data["servers"]:
Permissions_Servers.update_role_permission( PermissionsServers.update_role_permission(role_id, server, permissions_mask)
role_id, server, permissions_mask
)
# TODO: This is horribly inefficient and we should be using bulk queries # TODO: This is horribly inefficient and we should be using bulk queries
# but im going for functionality at this point # 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: if up_data:
helper_roles.update_role(role_id, up_data) HelperRoles.update_role(role_id, up_data)
@staticmethod @staticmethod
def add_role(role_name): def add_role(role_name):
return helper_roles.add_role(role_name) return HelperRoles.add_role(role_name)
def remove_role(self, role_id): def remove_role(self, role_id):
role_data = Roles_Controller.get_role_with_servers(role_id) role_data = RolesController.get_role_with_servers(role_id)
Permissions_Servers.delete_roles_permissions(role_id, role_data["servers"]) PermissionsServers.delete_roles_permissions(role_id, role_data["servers"])
self.users_helper.remove_roles_from_role_id(role_id) self.users_helper.remove_roles_from_role_id(role_id)
return self.roles_helper.remove_role(role_id) return self.roles_helper.remove_role(role_id)
@staticmethod @staticmethod
def role_id_exists(role_id): def role_id_exists(role_id):
return helper_roles.role_id_exists(role_id) return HelperRoles.role_id_exists(role_id)
@staticmethod @staticmethod
def get_role_with_servers(role_id): def get_role_with_servers(role_id):
role = helper_roles.get_role(role_id) role = HelperRoles.get_role(role_id)
if role: 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 # TODO: this query needs to be narrower
servers = set() servers = set()
for s in servers_query: for s in servers_query:

View File

@ -1,53 +1,53 @@
import logging import logging
from app.classes.models.server_permissions import ( from app.classes.models.server_permissions import (
Permissions_Servers, PermissionsServers,
Enum_Permissions_Server, EnumPermissionsServer,
) )
from app.classes.models.users import helper_users, ApiKeys from app.classes.models.users import HelperUsers, ApiKeys
from app.classes.models.roles import helper_roles from app.classes.models.roles import HelperRoles
from app.classes.models.servers import helper_servers from app.classes.models.servers import HelperServers
from app.classes.shared.main_models import db_shortcuts from app.classes.shared.main_models import DatabaseShortcuts
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Server_Perms_Controller: class ServerPermsController:
@staticmethod @staticmethod
def get_server_user_list(server_id): 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 @staticmethod
def list_defined_permissions(): def list_defined_permissions():
permissions_list = Permissions_Servers.get_permissions_list() permissions_list = PermissionsServers.get_permissions_list()
return permissions_list return permissions_list
@staticmethod @staticmethod
def get_mask_permissions(role_id, server_id): 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 return permissions_mask
@staticmethod @staticmethod
def get_role_permissions(role_id): 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 return permissions_list
@staticmethod @staticmethod
def add_role_server(server_id, role_id, rs_permissions="00000000"): 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 @staticmethod
def get_server_roles(server_id): def get_server_roles(server_id):
return Permissions_Servers.get_server_roles(server_id) return PermissionsServers.get_server_roles(server_id)
@staticmethod @staticmethod
def backup_role_swap(old_server_id, new_server_id): 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: for role in role_list:
Permissions_Servers.add_role_server( PermissionsServers.add_role_server(
new_server_id, new_server_id,
role.role_id, role.role_id,
Permissions_Servers.get_permissions_mask( PermissionsServers.get_permissions_mask(
int(role.role_id), int(old_server_id) int(role.role_id), int(old_server_id)
), ),
) )
@ -60,57 +60,62 @@ class Server_Perms_Controller:
# ********************************************************************************** # **********************************************************************************
@staticmethod @staticmethod
def get_permissions_mask(role_id, server_id): 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 @staticmethod
def set_permission( 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 permission_mask, permission_tested, value
) )
@staticmethod @staticmethod
def get_role_permissions_list(role_id): 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 @staticmethod
def get_user_id_permissions_list(user_id: str, server_id: str): 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 @staticmethod
def get_api_key_id_permissions_list(key_id: str, server_id: str): def get_api_key_id_permissions_list(key_id: str, server_id: str):
key = helper_users.get_user_api_key(key_id) key = HelperUsers.get_user_api_key(key_id)
return Permissions_Servers.get_api_key_permissions_list(key, server_id) return PermissionsServers.get_api_key_permissions_list(key, server_id)
@staticmethod @staticmethod
def get_api_key_permissions_list(key: ApiKeys, server_id: str): 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 @staticmethod
def get_authorized_servers_stats_from_roles(user_id): 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 = [] roles_list = []
role_server = [] role_server = []
authorized_servers = [] authorized_servers = []
server_data = [] server_data = []
for u in user_roles: for user in user_roles:
roles_list.append(helper_roles.get_role(u.role_id)) roles_list.append(HelperRoles.get_role(user.role_id))
for r in roles_list: for role in roles_list:
role_test = Permissions_Servers.get_role_servers_from_role_id( role_test = PermissionsServers.get_role_servers_from_role_id(
r.get("role_id") role.get("role_id")
) )
for t in role_test: for test in role_test:
role_server.append(t) role_server.append(test)
for s in role_server: for server in role_server:
authorized_servers.append(helper_servers.get_server_data_by_id(s.server_id)) authorized_servers.append(
HelperServers.get_server_data_by_id(server.server_id)
)
for s in authorized_servers: for server in authorized_servers:
latest = helper_servers.get_latest_server_stats(s.get("server_id")) latest = HelperServers.get_latest_server_stats(server.get("server_id"))
server_data.append( 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 return server_data

View File

@ -2,20 +2,20 @@ import os
import logging import logging
import json import json
from app.classes.controllers.roles_controller import Roles_Controller from app.classes.controllers.roles_controller import RolesController
from app.classes.models.servers import helper_servers from app.classes.models.servers import HelperServers
from app.classes.models.users import helper_users, ApiKeys from app.classes.models.users import HelperUsers, ApiKeys
from app.classes.models.server_permissions import ( from app.classes.models.server_permissions import (
Permissions_Servers, PermissionsServers,
Enum_Permissions_Server, EnumPermissionsServer,
) )
from app.classes.shared.helpers import Helpers 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__) logger = logging.getLogger(__name__)
class Servers_Controller: class ServersController:
def __init__(self, servers_helper): def __init__(self, servers_helper):
self.servers_helper = servers_helper self.servers_helper = servers_helper
@ -50,80 +50,82 @@ class Servers_Controller:
@staticmethod @staticmethod
def get_server_obj(server_id): def get_server_obj(server_id):
return helper_servers.get_server_obj(server_id) return HelperServers.get_server_obj(server_id)
@staticmethod @staticmethod
def update_server(server_obj): def update_server(server_obj):
return helper_servers.update_server(server_obj) return HelperServers.update_server(server_obj)
@staticmethod @staticmethod
def set_download(server_id): def set_download(server_id):
return helper_servers.set_download(server_id) return HelperServers.set_download(server_id)
@staticmethod @staticmethod
def finish_download(server_id): def finish_download(server_id):
return helper_servers.finish_download(server_id) return HelperServers.finish_download(server_id)
@staticmethod @staticmethod
def get_download_status(server_id): 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): 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: for role in roles_list:
role_id = role.role_id 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} role_data["servers"] = {server_id}
Permissions_Servers.delete_roles_permissions(role_id, role_data["servers"]) PermissionsServers.delete_roles_permissions(role_id, role_data["servers"])
Permissions_Servers.remove_roles_of_server(server_id) PermissionsServers.remove_roles_of_server(server_id)
self.servers_helper.remove_server(server_id) self.servers_helper.remove_server(server_id)
@staticmethod @staticmethod
def get_server_data_by_id(server_id): 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 # Servers Methods
# ********************************************************************************** # **********************************************************************************
@staticmethod @staticmethod
def get_all_defined_servers(): def get_all_defined_servers():
return helper_servers.get_all_defined_servers() return HelperServers.get_all_defined_servers()
@staticmethod @staticmethod
def get_authorized_servers(user_id): def get_authorized_servers(user_id):
server_data = [] server_data = []
user_roles = helper_users.user_role_query(user_id) user_roles = HelperUsers.user_role_query(user_id)
for us in user_roles: for user in user_roles:
role_servers = Permissions_Servers.get_role_servers_from_role_id(us.role_id) role_servers = PermissionsServers.get_role_servers_from_role_id(
user.role_id
)
for role in role_servers: 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 return server_data
@staticmethod @staticmethod
def get_all_servers_stats(): def get_all_servers_stats():
return helper_servers.get_all_servers_stats() return HelperServers.get_all_servers_stats()
@staticmethod @staticmethod
def get_authorized_servers_stats_api_key(api_key: ApiKeys): def get_authorized_servers_stats_api_key(api_key: ApiKeys):
server_data = [] server_data = []
authorized_servers = Servers_Controller.get_authorized_servers( authorized_servers = ServersController.get_authorized_servers(
api_key.user.user_id api_key.user.user_id
) )
for s in authorized_servers: for server in authorized_servers:
latest = helper_servers.get_latest_server_stats(s.get("server_id")) latest = HelperServers.get_latest_server_stats(server.get("server_id"))
key_permissions = Permissions_Servers.get_api_key_permissions_list( key_permissions = PermissionsServers.get_api_key_permissions_list(
api_key, s.get("server_id") api_key, server.get("server_id")
) )
if Enum_Permissions_Server.Commands in key_permissions: if EnumPermissionsServer.COMMANDS in key_permissions:
user_command_permission = True user_command_permission = True
else: else:
user_command_permission = False user_command_permission = False
server_data.append( server_data.append(
{ {
"server_data": s, "server_data": server,
"stats": db_shortcuts.return_rows(latest)[0], "stats": DatabaseShortcuts.return_rows(latest)[0],
"user_command_permission": user_command_permission, "user_command_permission": user_command_permission,
} }
) )
@ -132,22 +134,22 @@ class Servers_Controller:
@staticmethod @staticmethod
def get_authorized_servers_stats(user_id): def get_authorized_servers_stats(user_id):
server_data = [] server_data = []
authorized_servers = Servers_Controller.get_authorized_servers(user_id) authorized_servers = ServersController.get_authorized_servers(user_id)
for s in authorized_servers: for server in authorized_servers:
latest = helper_servers.get_latest_server_stats(s.get("server_id")) latest = HelperServers.get_latest_server_stats(server.get("server_id"))
# TODO # TODO
user_permissions = Permissions_Servers.get_user_id_permissions_list( user_permissions = PermissionsServers.get_user_id_permissions_list(
user_id, s.get("server_id") user_id, server.get("server_id")
) )
if Enum_Permissions_Server.Commands in user_permissions: if EnumPermissionsServer.COMMANDS in user_permissions:
user_command_permission = True user_command_permission = True
else: else:
user_command_permission = False user_command_permission = False
server_data.append( server_data.append(
{ {
"server_data": s, "server_data": server,
"stats": db_shortcuts.return_rows(latest)[0], "stats": DatabaseShortcuts.return_rows(latest)[0],
"user_command_permission": user_command_permission, "user_command_permission": user_command_permission,
} }
) )
@ -156,28 +158,28 @@ class Servers_Controller:
@staticmethod @staticmethod
def get_server_friendly_name(server_id): 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 # Servers_Stats Methods
# ********************************************************************************** # **********************************************************************************
@staticmethod @staticmethod
def get_server_stats_by_id(server_id): 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 @staticmethod
def server_id_exists(server_id): def server_id_exists(server_id):
return helper_servers.server_id_exists(server_id) return HelperServers.server_id_exists(server_id)
@staticmethod @staticmethod
def get_server_type_by_id(server_id): 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 @staticmethod
def server_id_authorized(server_id_a, user_id): 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 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 role.role_id
): ):
if str(server_id_a) == str(server_id_b.server_id): if str(server_id_a) == str(server_id_b.server_id):
@ -186,12 +188,12 @@ class Servers_Controller:
@staticmethod @staticmethod
def is_crashed(server_id): def is_crashed(server_id):
return helper_servers.is_crashed(server_id) return HelperServers.is_crashed(server_id)
@staticmethod @staticmethod
def server_id_authorized_api_key(server_id: str, api_key: ApiKeys) -> bool: def server_id_authorized_api_key(server_id: str, api_key: ApiKeys) -> bool:
# TODO # 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 # There is no view server permission
# permission_helper.both_have_perm(api_key) # permission_helper.both_have_perm(api_key)
@ -199,30 +201,30 @@ class Servers_Controller:
return self.servers_helper.set_update(server_id, value) return self.servers_helper.set_update(server_id, value)
@staticmethod @staticmethod
def get_TTL_without_player(server_id): def get_ttl_without_player(server_id):
return helper_servers.get_TTL_without_player(server_id) return HelperServers.get_ttl_without_player(server_id)
@staticmethod @staticmethod
def can_stop_no_players(server_id, time_limit): 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): def set_waiting_start(self, server_id, value):
self.servers_helper.set_waiting_start(server_id, value) self.servers_helper.set_waiting_start(server_id, value)
@staticmethod @staticmethod
def get_waiting_start(server_id): def get_waiting_start(server_id):
return helper_servers.get_waiting_start(server_id) return HelperServers.get_waiting_start(server_id)
@staticmethod @staticmethod
def get_update_status(server_id): def get_update_status(server_id):
return helper_servers.get_update_status(server_id) return HelperServers.get_update_status(server_id)
# ********************************************************************************** # **********************************************************************************
# Servers Helpers Methods # Servers Helpers Methods
# ********************************************************************************** # **********************************************************************************
@staticmethod @staticmethod
def get_banned_players(server_id): 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"] server_path = stats["server_id"]["path"]
path = os.path.join(server_path, "banned-players.json") path = os.path.join(server_path, "banned-players.json")
@ -239,7 +241,7 @@ class Servers_Controller:
return json.loads(content) return json.loads(content)
def check_for_old_logs(self): def check_for_old_logs(self):
servers = helper_servers.get_all_defined_servers() servers = HelperServers.get_all_defined_servers()
for server in servers: for server in servers:
logs_path = os.path.split(server["log_path"])[0] logs_path = os.path.split(server["log_path"])[0]
latest_log_file = os.path.split(server["log_path"])[1] latest_log_file = os.path.split(server["log_path"])[1]

View File

@ -1,16 +1,16 @@
import logging import logging
from typing import Optional 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 ( from app.classes.models.crafty_permissions import (
Permissions_Crafty, PermissionsCrafty,
Enum_Permissions_Crafty, EnumPermissionsCrafty,
) )
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Users_Controller: class UsersController:
def __init__(self, helper, users_helper, authentication): def __init__(self, helper, users_helper, authentication):
self.helper = helper self.helper = helper
self.users_helper = users_helper self.users_helper = users_helper
@ -21,42 +21,42 @@ class Users_Controller:
# ********************************************************************************** # **********************************************************************************
@staticmethod @staticmethod
def get_all_users(): def get_all_users():
return helper_users.get_all_users() return HelperUsers.get_all_users()
@staticmethod @staticmethod
def get_id_by_name(username): def get_id_by_name(username):
return helper_users.get_user_id_by_name(username) return HelperUsers.get_user_id_by_name(username)
@staticmethod @staticmethod
def get_user_lang_by_id(user_id): 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 @staticmethod
def get_user_by_id(user_id): def get_user_by_id(user_id):
return helper_users.get_user(user_id) return HelperUsers.get_user(user_id)
@staticmethod @staticmethod
def update_server_order(user_id, user_server_order): 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 @staticmethod
def get_server_order(user_id): def get_server_order(user_id):
return helper_users.get_server_order(user_id) return HelperUsers.get_server_order(user_id)
@staticmethod @staticmethod
def user_query(user_id): def user_query(user_id):
return helper_users.user_query(user_id) return HelperUsers.user_query(user_id)
@staticmethod @staticmethod
def set_support_path(user_id, support_path): 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): def update_user(self, user_id: str, user_data=None, user_crafty_data=None):
if user_crafty_data is None: if user_crafty_data is None:
user_crafty_data = {} user_crafty_data = {}
if user_data is None: if user_data is None:
user_data = {} user_data = {}
base_data = helper_users.get_user(user_id) base_data = HelperUsers.get_user(user_id)
up_data = {} up_data = {}
added_roles = set() added_roles = set()
removed_roles = set() removed_roles = set()
@ -76,26 +76,26 @@ class Users_Controller:
up_data["hints"] = user_data["hints"] up_data["hints"] = user_data["hints"]
logger.debug(f"user: {user_data} +role:{added_roles} -role:{removed_roles}") logger.debug(f"user: {user_data} +role:{added_roles} -role:{removed_roles}")
for role in added_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") permissions_mask = user_crafty_data.get("permissions_mask", "000")
if "server_quantity" in user_crafty_data: if "server_quantity" in user_crafty_data:
limit_server_creation = user_crafty_data["server_quantity"][ 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"][ 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"][ limit_role_creation = user_crafty_data["server_quantity"][
Enum_Permissions_Crafty.Roles_Config.name EnumPermissionsCrafty.ROLES_CONFIG.name
] ]
else: else:
limit_server_creation = 0 limit_server_creation = 0
limit_user_creation = 0 limit_user_creation = 0
limit_role_creation = 0 limit_role_creation = 0
Permissions_Crafty.add_or_update_user( PermissionsCrafty.add_or_update_user(
user_id, user_id,
permissions_mask, permissions_mask,
limit_server_creation, limit_server_creation,
@ -131,7 +131,7 @@ class Users_Controller:
enabled: bool = True, enabled: bool = True,
superuser: bool = False, superuser: bool = False,
): ):
return helper_users.add_rawpass_user( return HelperUsers.add_rawpass_user(
username, username,
password=password, password=password,
email=email, email=email,
@ -144,15 +144,15 @@ class Users_Controller:
@staticmethod @staticmethod
def user_id_exists(user_id): def user_id_exists(user_id):
return helper_users.user_id_exists(user_id) return HelperUsers.user_id_exists(user_id)
@staticmethod @staticmethod
def set_prepare(user_id): def set_prepare(user_id):
return helper_users.set_prepare(user_id) return HelperUsers.set_prepare(user_id)
@staticmethod @staticmethod
def stop_prepare(user_id): 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: def get_user_id_by_api_token(self, token: str) -> str:
token_data = self.authentication.check_no_iat(token) token_data = self.authentication.check_no_iat(token)
@ -172,11 +172,11 @@ class Users_Controller:
@staticmethod @staticmethod
def get_user_roles_id(user_id): 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 @staticmethod
def get_user_roles_names(user_id): 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): def add_role_to_user(self, user_id, role_id):
return self.users_helper.add_role_to_user(user_id, role_id) return self.users_helper.add_role_to_user(user_id, role_id)
@ -186,7 +186,7 @@ class Users_Controller:
@staticmethod @staticmethod
def user_role_query(user_id): def user_role_query(user_id):
return helper_users.user_role_query(user_id) return HelperUsers.user_role_query(user_id)
# ********************************************************************************** # **********************************************************************************
# Api Keys Methods # Api Keys Methods
@ -194,11 +194,11 @@ class Users_Controller:
@staticmethod @staticmethod
def get_user_api_keys(user_id: str): 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 @staticmethod
def get_user_api_key(key_id: str): 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( def add_user_api_key(
self, self,

View File

@ -37,34 +37,45 @@ class BedrockPing:
@staticmethod @staticmethod
def __slice(in_bytes, pattern): def __slice(in_bytes, pattern):
ret = [] ret = []
bi = 0 # bytes index bytes_index = 0
pi = 0 # pattern index pattern_index = 0
while bi < len(in_bytes): while bytes_index < len(in_bytes):
try: try:
f = BedrockPing.fields[pattern[pi]] field = BedrockPing.fields[pattern[pattern_index]]
except IndexError as index_error: except IndexError as index_error:
raise IndexError( raise IndexError(
"Ran out of pattern with additional bytes remaining" "Ran out of pattern with additional bytes remaining"
) from index_error ) from index_error
if pattern[pi] == "string": if pattern[pattern_index] == "string":
shl = f[0] # string header length string_header_length = field[0]
sl = int.from_bytes( string_length = int.from_bytes(
in_bytes[bi : bi + shl], BedrockPing.byte_order, signed=f[1] in_bytes[bytes_index : bytes_index + string_header_length],
) # string length BedrockPing.byte_order,
l = shl + sl signed=field[1],
ret.append(in_bytes[bi + shl : bi + shl + sl].decode("ascii")) )
elif pattern[pi] == "magic": length = string_header_length + string_length
l = f[0] # length of field ret.append(
ret.append(in_bytes[bi : bi + l]) 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: else:
l = f[0] # length of field length = field[0]
ret.append( ret.append(
int.from_bytes( 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 bytes_index += length
pi += 1 pattern_index += 1
return ret return ret
@staticmethod @staticmethod
@ -115,6 +126,6 @@ class BedrockPing:
return self.__recvpong() return self.__recvpong()
except ValueError as e: except ValueError as e:
print( print(
f"E: {e}, checking next packet. Retries remaining: {rtr}/{retries}" f"E: {e}, checking next packet. Retries remaining: {rtr}/{retries}"
) )
rtr -= 1 rtr -= 1

View File

@ -78,8 +78,8 @@ class Players(list):
def report(self): def report(self):
players = [] players = []
for x in self: for player in self:
players.append(str(x)) players.append(str(player))
r_data = {"online": self.online, "max": self.max, "players": players} 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 # For the rest of requests see wiki.vg/Protocol
def ping_bedrock(ip, port): def ping_bedrock(ip, port):
rd = random.Random() rand = random.Random()
try: try:
# pylint: disable=consider-using-f-string # pylint: disable=consider-using-f-string
rd.seed("".join(re.findall("..", "%012x" % uuid.getnode()))) rand.seed("".join(re.findall("..", "%012x" % uuid.getnode())))
client_guid = uuid.UUID(int=rd.getrandbits(32)).int client_guid = uuid.UUID(int=rand.getrandbits(32)).int
except: except:
client_guid = 0 client_guid = 0
try: try:

View File

@ -9,25 +9,25 @@ class ServerProps:
def _parse(self): def _parse(self):
# Loads and parses the file specified in self.filepath # Loads and parses the file specified in self.filepath
with open(self.filepath, encoding="utf-8") as fp: with open(self.filepath, encoding="utf-8") as full_path:
line = fp.readline() line = full_path.readline()
d = {} dictionary = {}
if os.path.exists(".header"): if os.path.exists(".header"):
os.remove(".header") os.remove(".header")
while line: while line:
if "#" != line[0]: if "#" != line[0]:
s = line string = line
s1 = s[: s.find("=")] string1 = string[: string.find("=")]
if "\n" in s: if "\n" in string:
s2 = s[s.find("=") + 1 : s.find("\n")] string2 = string[string.find("=") + 1 : string.find("\n")]
else: else:
s2 = s[s.find("=") + 1 :] string2 = string[string.find("=") + 1 :]
d[s1] = s2 dictionary[string1] = string2
else: else:
with open(".header", "a+", encoding="utf-8") as h: with open(".header", "a+", encoding="utf-8") as header:
h.write(line) header.write(line)
line = fp.readline() line = full_path.readline()
return d return dictionary
def print(self): def print(self):
# Prints the properties dictionary (using pprint) # Prints the properties dictionary (using pprint)

View File

@ -6,8 +6,8 @@ import logging
from datetime import datetime from datetime import datetime
import requests import requests
from app.classes.controllers.servers_controller import Servers_Controller from app.classes.controllers.servers_controller import ServersController
from app.classes.models.server_permissions import Permissions_Servers from app.classes.models.server_permissions import PermissionsServers
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -21,16 +21,16 @@ class ServerJars:
full_url = f"{self.base_url}{call_url}" full_url = f"{self.base_url}{call_url}"
try: 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 {} return {}
except Exception as e: except Exception as e:
logger.error(f"Unable to connect to serverjar.com api due to error: {e}") logger.error(f"Unable to connect to serverjar.com api due to error: {e}")
return {} return {}
try: try:
api_data = json.loads(r.content) api_data = json.loads(response.content)
except Exception as e: except Exception as e:
logger.error(f"Unable to parse serverjar.com api result due to error: {e}") logger.error(f"Unable to parse serverjar.com api result due to error: {e}")
return {} return {}
@ -60,37 +60,14 @@ class ServerJars:
data = self._read_cache() data = self._read_cache()
return data.get("servers") 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): def _check_api_alive(self):
logger.info("Checking serverjars.com API status") logger.info("Checking serverjars.com API status")
check_url = f"{self.base_url}/api/fetchTypes" check_url = f"{self.base_url}/api/fetchTypes"
try: 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") logger.info("Serverjars.com API is alive")
return True return True
except Exception as e: except Exception as e:
@ -170,13 +147,13 @@ class ServerJars:
# delaying download for server register to finish # delaying download for server register to finish
time.sleep(3) time.sleep(3)
fetch_url = f"{self.base_url}/api/fetchJar/{server}/{version}" 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 need to make sure the server is registered before
# we submit a db update for it's stats. # we submit a db update for it's stats.
while True: while True:
try: try:
Servers_Controller.set_download(server_id) ServersController.set_download(server_id)
for user in server_users: for user in server_users:
self.helper.websocket_helper.broadcast_user( self.helper.websocket_helper.broadcast_user(
user, "send_start_reload", {} user, "send_start_reload", {}
@ -191,7 +168,7 @@ class ServerJars:
try: try:
with open(path, "wb") as output: with open(path, "wb") as output:
shutil.copyfileobj(r.raw, output) shutil.copyfileobj(r.raw, output)
Servers_Controller.finish_download(server_id) ServersController.finish_download(server_id)
for user in server_users: for user in server_users:
self.helper.websocket_helper.broadcast_user( self.helper.websocket_helper.broadcast_user(
@ -204,8 +181,8 @@ class ServerJars:
return True return True
except Exception as e: except Exception as e:
logger.error(f"Unable to save jar to {path} due to error:{e}") logger.error(f"Unable to save jar to {path} due to error:{e}")
Servers_Controller.finish_download(server_id) ServersController.finish_download(server_id)
server_users = Permissions_Servers.get_server_user_list(server_id) server_users = PermissionsServers.get_server_user_list(server_id)
for user in server_users: for user in server_users:
self.helper.websocket_helper.broadcast_user( self.helper.websocket_helper.broadcast_user(
user, "notification", "Executable download finished" user, "notification", "Executable download finished"

View File

@ -5,8 +5,8 @@ import base64
import psutil import psutil
from app.classes.minecraft.mc_ping import ping from app.classes.minecraft.mc_ping import ping
from app.classes.models.management import Host_Stats from app.classes.models.management import HostStats
from app.classes.models.servers import helper_servers from app.classes.models.servers import HelperServers
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -121,7 +121,7 @@ class Stats:
def get_server_players(self, server_id): 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}") logger.info(f"Getting players for server {server}")
@ -134,7 +134,7 @@ class Stats:
server_port = server["server_port"] server_port = server["server_port"]
logger.debug(f"Pinging {internal_ip} on port {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)) int_mc_ping = ping(internal_ip, int(server_port))
ping_data = {} ping_data = {}
@ -174,7 +174,7 @@ class Stats:
return ping_data return ping_data
@staticmethod @staticmethod
def parse_server_RakNet_ping(ping_obj: object): def parse_server_raknet_ping(ping_obj: object):
try: try:
server_icon = base64.encodebytes(ping_obj["icon"]) server_icon = base64.encodebytes(ping_obj["icon"])
@ -196,17 +196,17 @@ class Stats:
stats_to_send = self.get_node_stats() stats_to_send = self.get_node_stats()
node_stats = stats_to_send.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"), HostStats.boot_time: node_stats.get("boot_time", "Unknown"),
Host_Stats.cpu_usage: round(node_stats.get("cpu_usage", 0), 2), HostStats.cpu_usage: round(node_stats.get("cpu_usage", 0), 2),
Host_Stats.cpu_cores: node_stats.get("cpu_count", 0), HostStats.cpu_cores: node_stats.get("cpu_count", 0),
Host_Stats.cpu_cur_freq: node_stats.get("cpu_cur_freq", 0), HostStats.cpu_cur_freq: node_stats.get("cpu_cur_freq", 0),
Host_Stats.cpu_max_freq: node_stats.get("cpu_max_freq", 0), HostStats.cpu_max_freq: node_stats.get("cpu_max_freq", 0),
Host_Stats.mem_usage: node_stats.get("mem_usage", "0 MB"), HostStats.mem_usage: node_stats.get("mem_usage", "0 MB"),
Host_Stats.mem_percent: node_stats.get("mem_percent", 0), HostStats.mem_percent: node_stats.get("mem_percent", 0),
Host_Stats.mem_total: node_stats.get("mem_total", "0 MB"), HostStats.mem_total: node_stats.get("mem_total", "0 MB"),
Host_Stats.disk_json: node_stats.get("disk_data", "{}"), HostStats.disk_json: node_stats.get("disk_data", "{}"),
} }
).execute() ).execute()
@ -239,7 +239,7 @@ class Stats:
now = datetime.datetime.now() now = datetime.datetime.now()
last_week = now.day - max_age 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() # Server_Stats.delete().where(Server_Stats.created < last_week).execute()

View File

@ -8,7 +8,7 @@ from peewee import (
) )
from app.classes.models.base_model import BaseModel 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 from app.classes.shared.permission_helper import PermissionHelper
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -16,7 +16,7 @@ logger = logging.getLogger(__name__)
# ********************************************************************************** # **********************************************************************************
# User_Crafty Class # User_Crafty Class
# ********************************************************************************** # **********************************************************************************
class User_Crafty(BaseModel): class UserCrafty(BaseModel):
user_id = ForeignKeyField(Users, backref="users_crafty") user_id = ForeignKeyField(Users, backref="users_crafty")
permissions = CharField(default="00000000") permissions = CharField(default="00000000")
limit_server_creation = IntegerField(default=-1) limit_server_creation = IntegerField(default=-1)
@ -33,33 +33,33 @@ class User_Crafty(BaseModel):
# ********************************************************************************** # **********************************************************************************
# Crafty Permissions Class # Crafty Permissions Class
# ********************************************************************************** # **********************************************************************************
class Enum_Permissions_Crafty(Enum): class EnumPermissionsCrafty(Enum):
Server_Creation = 0 SERVER_CREATION = 0
User_Config = 1 USER_CONFIG = 1
Roles_Config = 2 ROLES_CONFIG = 2
class Permissions_Crafty: class PermissionsCrafty:
# ********************************************************************************** # **********************************************************************************
# Crafty Permissions Methods # Crafty Permissions Methods
# ********************************************************************************** # **********************************************************************************
@staticmethod @staticmethod
def get_permissions_list(): def get_permissions_list():
permissions_list = [] permissions_list = []
for member in Enum_Permissions_Crafty.__members__.items(): for member in EnumPermissionsCrafty.__members__.items():
permissions_list.append(member[1]) permissions_list.append(member[1])
return permissions_list return permissions_list
@staticmethod @staticmethod
def get_permissions(permissions_mask): def get_permissions(permissions_mask):
permissions_list = [] permissions_list = []
for member in Enum_Permissions_Crafty.__members__.items(): for member in EnumPermissionsCrafty.__members__.items():
if Permissions_Crafty.has_permission(permissions_mask, member[1]): if PermissionsCrafty.has_permission(permissions_mask, member[1]):
permissions_list.append(member[1]) permissions_list.append(member[1])
return permissions_list return permissions_list
@staticmethod @staticmethod
def has_permission(permission_mask, permission_tested: Enum_Permissions_Crafty): def has_permission(permission_mask, permission_tested: EnumPermissionsCrafty):
result = False result = False
if permission_mask[permission_tested.value] == "1": if permission_mask[permission_tested.value] == "1":
result = True result = True
@ -67,40 +67,40 @@ class Permissions_Crafty:
@staticmethod @staticmethod
def set_permission( def set_permission(
permission_mask, permission_tested: Enum_Permissions_Crafty, value permission_mask, permission_tested: EnumPermissionsCrafty, value
): ):
l = list(permission_mask) lst = list(permission_mask)
l[permission_tested.value] = str(value) lst[permission_tested.value] = str(value)
permission_mask = "".join(l) permission_mask = "".join(lst)
return permission_mask return permission_mask
@staticmethod @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] return permission_mask[permission_tested.value]
@staticmethod @staticmethod
def get_crafty_permissions_mask(user_id): def get_crafty_permissions_mask(user_id):
permissions_mask = "" permissions_mask = ""
user_crafty = Permissions_Crafty.get_User_Crafty(user_id) user_crafty = PermissionsCrafty.get_user_crafty(user_id)
permissions_mask = user_crafty.permissions permissions_mask = user_crafty.permissions
return permissions_mask return permissions_mask
@staticmethod @staticmethod
def get_all_permission_quantity_list(): def get_all_permission_quantity_list():
quantity_list = { quantity_list = {
Enum_Permissions_Crafty.Server_Creation.name: -1, EnumPermissionsCrafty.SERVER_CREATION.name: -1,
Enum_Permissions_Crafty.User_Config.name: -1, EnumPermissionsCrafty.USER_CONFIG.name: -1,
Enum_Permissions_Crafty.Roles_Config.name: -1, EnumPermissionsCrafty.ROLES_CONFIG.name: -1,
} }
return quantity_list return quantity_list
@staticmethod @staticmethod
def get_permission_quantity_list(user_id): 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 = { quantity_list = {
Enum_Permissions_Crafty.Server_Creation.name: user_crafty.limit_server_creation, # pylint: disable=line-too-long EnumPermissionsCrafty.SERVER_CREATION.name: user_crafty.limit_server_creation, # pylint: disable=line-too-long
Enum_Permissions_Crafty.User_Config.name: user_crafty.limit_user_creation, EnumPermissionsCrafty.USER_CONFIG.name: user_crafty.limit_user_creation,
Enum_Permissions_Crafty.Roles_Config.name: user_crafty.limit_role_creation, EnumPermissionsCrafty.ROLES_CONFIG.name: user_crafty.limit_role_creation,
} }
return quantity_list return quantity_list
@ -108,31 +108,29 @@ class Permissions_Crafty:
# User_Crafty Methods # User_Crafty Methods
# ********************************************************************************** # **********************************************************************************
@staticmethod @staticmethod
def get_User_Crafty(user_id): def get_user_crafty(user_id):
try: try:
user_crafty = ( user_crafty = UserCrafty.select().where(UserCrafty.user_id == user_id).get()
User_Crafty.select().where(User_Crafty.user_id == user_id).get()
)
except DoesNotExist: except DoesNotExist:
user_crafty = User_Crafty.insert( user_crafty = UserCrafty.insert(
{ {
User_Crafty.user_id: user_id, UserCrafty.user_id: user_id,
User_Crafty.permissions: "000", UserCrafty.permissions: "000",
User_Crafty.limit_server_creation: 0, UserCrafty.limit_server_creation: 0,
User_Crafty.limit_user_creation: 0, UserCrafty.limit_user_creation: 0,
User_Crafty.limit_role_creation: 0, UserCrafty.limit_role_creation: 0,
User_Crafty.created_server: 0, UserCrafty.created_server: 0,
User_Crafty.created_user: 0, UserCrafty.created_user: 0,
User_Crafty.created_role: 0, UserCrafty.created_role: 0,
} }
).execute() ).execute()
user_crafty = Permissions_Crafty.get_User_Crafty(user_id) user_crafty = PermissionsCrafty.get_user_crafty(user_id)
return user_crafty return user_crafty
@staticmethod @staticmethod
def add_user_crafty(user_id, uc_permissions): def add_user_crafty(user_id, uc_permissions):
user_crafty = User_Crafty.insert( user_crafty = UserCrafty.insert(
{User_Crafty.user_id: user_id, User_Crafty.permissions: uc_permissions} {UserCrafty.user_id: user_id, UserCrafty.permissions: uc_permissions}
).execute() ).execute()
return user_crafty return user_crafty
@ -145,46 +143,44 @@ class Permissions_Crafty:
limit_role_creation, limit_role_creation,
): ):
try: try:
user_crafty = ( user_crafty = UserCrafty.select().where(UserCrafty.user_id == user_id).get()
User_Crafty.select().where(User_Crafty.user_id == user_id).get()
)
user_crafty.permissions = permissions_mask user_crafty.permissions = permissions_mask
user_crafty.limit_server_creation = limit_server_creation user_crafty.limit_server_creation = limit_server_creation
user_crafty.limit_user_creation = limit_user_creation user_crafty.limit_user_creation = limit_user_creation
user_crafty.limit_role_creation = limit_role_creation user_crafty.limit_role_creation = limit_role_creation
User_Crafty.save(user_crafty) UserCrafty.save(user_crafty)
except: except:
User_Crafty.insert( UserCrafty.insert(
{ {
User_Crafty.user_id: user_id, UserCrafty.user_id: user_id,
User_Crafty.permissions: permissions_mask, UserCrafty.permissions: permissions_mask,
User_Crafty.limit_server_creation: limit_server_creation, UserCrafty.limit_server_creation: limit_server_creation,
User_Crafty.limit_user_creation: limit_user_creation, UserCrafty.limit_user_creation: limit_user_creation,
User_Crafty.limit_role_creation: limit_role_creation, UserCrafty.limit_role_creation: limit_role_creation,
} }
).execute() ).execute()
@staticmethod @staticmethod
def get_created_quantity_list(user_id): 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 = { quantity_list = {
Enum_Permissions_Crafty.Server_Creation.name: user_crafty.created_server, EnumPermissionsCrafty.SERVER_CREATION.name: user_crafty.created_server,
Enum_Permissions_Crafty.User_Config.name: user_crafty.created_user, EnumPermissionsCrafty.USER_CONFIG.name: user_crafty.created_user,
Enum_Permissions_Crafty.Roles_Config.name: user_crafty.created_role, EnumPermissionsCrafty.ROLES_CONFIG.name: user_crafty.created_role,
} }
return quantity_list return quantity_list
@staticmethod @staticmethod
def get_crafty_limit_value(user_id, permission): 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] return quantity_list[permission]
@staticmethod @staticmethod
def can_add_in_crafty(user_id, permission): def can_add_in_crafty(user_id, permission):
user_crafty = Permissions_Crafty.get_User_Crafty(user_id) user_crafty = PermissionsCrafty.get_user_crafty(user_id)
can = Permissions_Crafty.has_permission(user_crafty.permissions, permission) can = PermissionsCrafty.has_permission(user_crafty.permissions, permission)
limit_list = Permissions_Crafty.get_permission_quantity_list(user_id) limit_list = PermissionsCrafty.get_permission_quantity_list(user_id)
quantity_list = Permissions_Crafty.get_created_quantity_list(user_id) quantity_list = PermissionsCrafty.get_created_quantity_list(user_id)
return can and ( return can and (
(quantity_list[permission.name] < limit_list[permission.name]) (quantity_list[permission.name] < limit_list[permission.name])
or limit_list[permission.name] == -1 or limit_list[permission.name] == -1
@ -192,26 +188,26 @@ class Permissions_Crafty:
@staticmethod @staticmethod
def add_server_creation(user_id): 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.created_server += 1
User_Crafty.save(user_crafty) UserCrafty.save(user_crafty)
return user_crafty.created_server return user_crafty.created_server
@staticmethod @staticmethod
def get_api_key_permissions_list(key: ApiKeys): 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: if user["superuser"] and key.superuser:
return Permissions_Crafty.get_permissions_list() return PermissionsCrafty.get_permissions_list()
else: else:
if user["superuser"]: if user["superuser"]:
user_permissions_mask = "111" user_permissions_mask = "111"
else: else:
user_permissions_mask = Permissions_Crafty.get_crafty_permissions_mask( user_permissions_mask = PermissionsCrafty.get_crafty_permissions_mask(
user["user_id"] user["user_id"]
) )
key_permissions_mask: str = key.crafty_permissions key_permissions_mask: str = key.crafty_permissions
permissions_mask = PermissionHelper.combine_masks( permissions_mask = PermissionHelper.combine_masks(
user_permissions_mask, key_permissions_mask user_permissions_mask, key_permissions_mask
) )
permissions_list = Permissions_Crafty.get_permissions(permissions_mask) permissions_list = PermissionsCrafty.get_permissions(permissions_mask)
return permissions_list return permissions_list

View File

@ -13,17 +13,17 @@ from peewee import (
from playhouse.shortcuts import model_to_dict from playhouse.shortcuts import model_to_dict
from app.classes.models.base_model import BaseModel 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.servers import Servers
from app.classes.models.server_permissions import Permissions_Servers from app.classes.models.server_permissions import PermissionsServers
from app.classes.shared.main_models import db_shortcuts from app.classes.shared.main_models import DatabaseShortcuts
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
# ********************************************************************************** # **********************************************************************************
# Audit_Log Class # Audit_Log Class
# ********************************************************************************** # **********************************************************************************
class Audit_Log(BaseModel): class AuditLog(BaseModel):
audit_id = AutoField() audit_id = AutoField()
created = DateTimeField(default=datetime.datetime.now) created = DateTimeField(default=datetime.datetime.now)
user_name = CharField(default="") user_name = CharField(default="")
@ -34,11 +34,14 @@ class Audit_Log(BaseModel):
) # When auditing global events, use server ID 0 ) # When auditing global events, use server ID 0
log_msg = TextField(default="") log_msg = TextField(default="")
class Meta:
table_name = "audit_log"
# ********************************************************************************** # **********************************************************************************
# Host_Stats Class # Host_Stats Class
# ********************************************************************************** # **********************************************************************************
class Host_Stats(BaseModel): class HostStats(BaseModel):
time = DateTimeField(default=datetime.datetime.now, index=True) time = DateTimeField(default=datetime.datetime.now, index=True)
boot_time = CharField(default="") boot_time = CharField(default="")
cpu_usage = FloatField(default=0) cpu_usage = FloatField(default=0)
@ -120,7 +123,7 @@ class Backups(BaseModel):
table_name = "backups" table_name = "backups"
class helpers_management: class HelpersManagement:
def __init__(self, database, helper): def __init__(self, database, helper):
self.database = database self.database = database
self.helper = helper self.helper = helper
@ -131,7 +134,7 @@ class helpers_management:
@staticmethod @staticmethod
def get_latest_hosts_stats(): def get_latest_hosts_stats():
# pylint: disable=no-member # 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) return model_to_dict(query)
# ********************************************************************************** # **********************************************************************************
@ -166,60 +169,60 @@ class helpers_management:
# ********************************************************************************** # **********************************************************************************
@staticmethod @staticmethod
def get_actity_log(): def get_actity_log():
q = Audit_Log.select() query = AuditLog.select()
return db_shortcuts.return_db_rows(q) return DatabaseShortcuts.return_db_rows(query)
def add_to_audit_log(self, user_id, log_msg, server_id=None, source_ip=None): 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} ") 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}" 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: for user in server_users:
self.helper.websocket_helper.broadcast_user(user, "notification", audit_msg) self.helper.websocket_helper.broadcast_user(user, "notification", audit_msg)
Audit_Log.insert( AuditLog.insert(
{ {
Audit_Log.user_name: user_data["username"], AuditLog.user_name: user_data["username"],
Audit_Log.user_id: user_id, AuditLog.user_id: user_id,
Audit_Log.server_id: server_id, AuditLog.server_id: server_id,
Audit_Log.log_msg: audit_msg, AuditLog.log_msg: audit_msg,
Audit_Log.source_ip: source_ip, AuditLog.source_ip: source_ip,
} }
).execute() ).execute()
# deletes records when they're more than 100 # 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: for item in ordered:
if not self.helper.get_setting("max_audit_entries"): if not self.helper.get_setting("max_audit_entries"):
max_entries = 300 max_entries = 300
else: else:
max_entries = self.helper.get_setting("max_audit_entries") max_entries = self.helper.get_setting("max_audit_entries")
if Audit_Log.select().count() > max_entries: if AuditLog.select().count() > max_entries:
Audit_Log.delete().where(Audit_Log.audit_id == item.audit_id).execute() AuditLog.delete().where(AuditLog.audit_id == item.audit_id).execute()
else: else:
return return
def add_to_audit_log_raw(self, user_name, user_id, server_id, log_msg, source_ip): 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, AuditLog.user_name: user_name,
Audit_Log.user_id: user_id, AuditLog.user_id: user_id,
Audit_Log.server_id: server_id, AuditLog.server_id: server_id,
Audit_Log.log_msg: log_msg, AuditLog.log_msg: log_msg,
Audit_Log.source_ip: source_ip, AuditLog.source_ip: source_ip,
} }
).execute() ).execute()
# deletes records when they're more than 100 # 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: for item in ordered:
# configurable through app/config/config.json # configurable through app/config/config.json
if not self.helper.get_setting("max_audit_entries"): if not self.helper.get_setting("max_audit_entries"):
max_entries = 300 max_entries = 300
else: else:
max_entries = self.helper.get_setting("max_audit_entries") max_entries = self.helper.get_setting("max_audit_entries")
if Audit_Log.select().count() > max_entries: if AuditLog.select().count() > max_entries:
Audit_Log.delete().where(Audit_Log.audit_id == item.audit_id).execute() AuditLog.delete().where(AuditLog.audit_id == item.audit_id).execute()
else: else:
return return
@ -363,17 +366,20 @@ class helpers_management:
if not new_row: if not new_row:
with self.database.atomic(): with self.database.atomic():
if backup_path is not None: if backup_path is not None:
u1 = ( server_rows = (
Servers.update(backup_path=backup_path) Servers.update(backup_path=backup_path)
.where(Servers.server_id == server_id) .where(Servers.server_id == server_id)
.execute() .execute()
) )
else: else:
u1 = 0 server_rows = 0
u2 = ( backup_rows = (
Backups.update(conf).where(Backups.server_id == server_id).execute() 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: else:
with self.database.atomic(): with self.database.atomic():
conf["server_id"] = server_id conf["server_id"] = server_id
@ -386,7 +392,7 @@ class helpers_management:
@staticmethod @staticmethod
def get_excluded_backup_dirs(server_id: int): 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 != "": if excluded_dirs is not None and excluded_dirs != "":
dir_list = excluded_dirs.split(",") dir_list = excluded_dirs.split(",")
else: else:

View File

@ -29,7 +29,7 @@ class Roles(BaseModel):
# ********************************************************************************** # **********************************************************************************
# Roles Helpers # Roles Helpers
# ********************************************************************************** # **********************************************************************************
class helper_roles: class HelperRoles:
def __init__(self, database): def __init__(self, database):
self.database = database self.database = database
@ -70,6 +70,6 @@ class helper_roles:
@staticmethod @staticmethod
def role_id_exists(role_id): def role_id_exists(role_id):
if not helper_roles.get_role(role_id): if not HelperRoles.get_role(role_id):
return False return False
return True return True

View File

@ -10,7 +10,7 @@ from peewee import (
from app.classes.models.base_model import BaseModel from app.classes.models.base_model import BaseModel
from app.classes.models.servers import Servers from app.classes.models.servers import Servers
from app.classes.models.roles import Roles 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 from app.classes.shared.permission_helper import PermissionHelper
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -18,7 +18,7 @@ logger = logging.getLogger(__name__)
# ********************************************************************************** # **********************************************************************************
# Role Servers Class # Role Servers Class
# ********************************************************************************** # **********************************************************************************
class Role_Servers(BaseModel): class RoleServers(BaseModel):
role_id = ForeignKeyField(Roles, backref="role_server") role_id = ForeignKeyField(Roles, backref="role_server")
server_id = ForeignKeyField(Servers, backref="role_server") server_id = ForeignKeyField(Servers, backref="role_server")
permissions = CharField(default="00000000") permissions = CharField(default="00000000")
@ -31,46 +31,46 @@ class Role_Servers(BaseModel):
# ********************************************************************************** # **********************************************************************************
# Servers Permissions Class # Servers Permissions Class
# ********************************************************************************** # **********************************************************************************
class Enum_Permissions_Server(Enum): class EnumPermissionsServer(Enum):
Commands = 0 COMMANDS = 0
Terminal = 1 TERMINAL = 1
Logs = 2 LOGS = 2
Schedule = 3 SCHEDULE = 3
Backup = 4 BACKUP = 4
Files = 5 FILES = 5
Config = 6 CONFIG = 6
Players = 7 PLAYERS = 7
class Permissions_Servers: class PermissionsServers:
@staticmethod @staticmethod
def get_or_create(role_id, server, permissions_mask): 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 role_id=role_id, server_id=server, permissions=permissions_mask
) )
@staticmethod @staticmethod
def get_permissions_list(): def get_permissions_list():
permissions_list = [] permissions_list = []
for member in Enum_Permissions_Server.__members__.items(): for member in EnumPermissionsServer.__members__.items():
permissions_list.append(member[1]) permissions_list.append(member[1])
return permissions_list return permissions_list
@staticmethod @staticmethod
def get_permissions(permissions_mask): def get_permissions(permissions_mask):
permissions_list = [] permissions_list = []
for member in Enum_Permissions_Server.__members__.items(): for member in EnumPermissionsServer.__members__.items():
if Permissions_Servers.has_permission(permissions_mask, member[1]): if PermissionsServers.has_permission(permissions_mask, member[1]):
permissions_list.append(member[1]) permissions_list.append(member[1])
return permissions_list return permissions_list
@staticmethod @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" return permission_mask[permission_tested.value] == "1"
@staticmethod @staticmethod
def set_permission( def set_permission(
permission_mask, permission_tested: Enum_Permissions_Server, value permission_mask, permission_tested: EnumPermissionsServer, value
): ):
list_perms = list(permission_mask) list_perms = list(permission_mask)
list_perms[permission_tested.value] = str(value) list_perms[permission_tested.value] = str(value)
@ -78,13 +78,13 @@ class Permissions_Servers:
return permission_mask return permission_mask
@staticmethod @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] return permission_mask[permission_tested.value]
@staticmethod @staticmethod
def get_token_permissions(permissions_mask, api_permissions_mask): def get_token_permissions(permissions_mask, api_permissions_mask):
permissions_list = [] permissions_list = []
for member in Enum_Permissions_Server.__members__.items(): for member in EnumPermissionsServer.__members__.items():
if PermissionHelper.both_have_perm( if PermissionHelper.both_have_perm(
permissions_mask, api_permissions_mask, member[1] permissions_mask, api_permissions_mask, member[1]
): ):
@ -96,31 +96,31 @@ class Permissions_Servers:
# ********************************************************************************** # **********************************************************************************
@staticmethod @staticmethod
def get_role_servers_from_role_id(roleid): 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 @staticmethod
def get_servers_from_role(role_id): def get_servers_from_role(role_id):
return ( return (
Role_Servers.select() RoleServers.select()
.join(Servers, JOIN.INNER) .join(Servers, JOIN.INNER)
.where(Role_Servers.role_id == role_id) .where(RoleServers.role_id == role_id)
) )
@staticmethod @staticmethod
def get_roles_from_server(server_id): def get_roles_from_server(server_id):
return ( return (
Role_Servers.select() RoleServers.select()
.join(Roles, JOIN.INNER) .join(Roles, JOIN.INNER)
.where(Role_Servers.server_id == server_id) .where(RoleServers.server_id == server_id)
) )
@staticmethod @staticmethod
def add_role_server(server_id, role_id, rs_permissions="00000000"): def add_role_server(server_id, role_id, rs_permissions="00000000"):
servers = Role_Servers.insert( servers = RoleServers.insert(
{ {
Role_Servers.server_id: server_id, RoleServers.server_id: server_id,
Role_Servers.role_id: role_id, RoleServers.role_id: role_id,
Role_Servers.permissions: rs_permissions, RoleServers.permissions: rs_permissions,
} }
).execute() ).execute()
return servers return servers
@ -129,9 +129,9 @@ class Permissions_Servers:
def get_permissions_mask(role_id, server_id): def get_permissions_mask(role_id, server_id):
permissions_mask = "" permissions_mask = ""
role_server = ( role_server = (
Role_Servers.select() RoleServers.select()
.where(Role_Servers.role_id == role_id) .where(RoleServers.role_id == role_id)
.where(Role_Servers.server_id == server_id) .where(RoleServers.server_id == server_id)
.get() .get()
) )
permissions_mask = role_server.permissions permissions_mask = role_server.permissions
@ -140,9 +140,7 @@ class Permissions_Servers:
@staticmethod @staticmethod
def get_server_roles(server_id): def get_server_roles(server_id):
role_list = [] role_list = []
roles = ( roles = RoleServers.select().where(RoleServers.server_id == server_id).execute()
Role_Servers.select().where(Role_Servers.server_id == server_id).execute()
)
for role in roles: for role in roles:
role_list.append(role.role_id) role_list.append(role.role_id)
return role_list return role_list
@ -150,72 +148,70 @@ class Permissions_Servers:
@staticmethod @staticmethod
def get_role_permissions_list(role_id): def get_role_permissions_list(role_id):
permissions_mask = "00000000" 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: if role_server is not None:
permissions_mask = role_server.permissions permissions_mask = role_server.permissions
permissions_list = Permissions_Servers.get_permissions(permissions_mask) permissions_list = PermissionsServers.get_permissions(permissions_mask)
return permissions_list return permissions_list
@staticmethod @staticmethod
def update_role_permission(role_id, server_id, permissions_mask): def update_role_permission(role_id, server_id, permissions_mask):
role_server = ( role_server = (
Role_Servers.select() RoleServers.select()
.where(Role_Servers.role_id == role_id) .where(RoleServers.role_id == role_id)
.where(Role_Servers.server_id == server_id) .where(RoleServers.server_id == server_id)
.get() .get()
) )
role_server.permissions = permissions_mask role_server.permissions = permissions_mask
Role_Servers.save(role_server) RoleServers.save(role_server)
@staticmethod @staticmethod
def delete_roles_permissions(role_id, removed_servers=None): def delete_roles_permissions(role_id, removed_servers=None):
if removed_servers is None: if removed_servers is None:
removed_servers = {} removed_servers = {}
return ( return (
Role_Servers.delete() RoleServers.delete()
.where(Role_Servers.role_id == role_id) .where(RoleServers.role_id == role_id)
.where(Role_Servers.server_id.in_(removed_servers)) .where(RoleServers.server_id.in_(removed_servers))
.execute() .execute()
) )
@staticmethod @staticmethod
def remove_roles_of_server(server_id): def remove_roles_of_server(server_id):
return ( return RoleServers.delete().where(RoleServers.server_id == server_id).execute()
Role_Servers.delete().where(Role_Servers.server_id == server_id).execute()
)
@staticmethod @staticmethod
def get_user_id_permissions_mask(user_id, server_id: str): def get_user_id_permissions_mask(user_id, server_id: str):
user = helper_users.get_user_model(user_id) user = HelperUsers.get_user_model(user_id)
return Permissions_Servers.get_user_permissions_mask(user, server_id) return PermissionsServers.get_user_permissions_mask(user, server_id)
@staticmethod @staticmethod
def get_user_permissions_mask(user: Users, server_id: str): def get_user_permissions_mask(user: Users, server_id: str):
if user.superuser: if user.superuser:
permissions_mask = "1" * len(Permissions_Servers.get_permissions_list()) permissions_mask = "1" * len(PermissionsServers.get_permissions_list())
else: 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_server = (
Role_Servers.select() RoleServers.select()
.where(Role_Servers.role_id.in_(roles_list)) .where(RoleServers.role_id.in_(roles_list))
.where(Role_Servers.server_id == server_id) .where(RoleServers.server_id == server_id)
.execute() .execute()
) )
try: try:
permissions_mask = role_server[0].permissions permissions_mask = role_server[0].permissions
except IndexError: except IndexError:
permissions_mask = "0" * len(Permissions_Servers.get_permissions_list()) permissions_mask = "0" * len(PermissionsServers.get_permissions_list())
return permissions_mask return permissions_mask
@staticmethod @staticmethod
def get_server_user_list(server_id): def get_server_user_list(server_id):
final_users = [] 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( super_users = Users.select().where(
Users.superuser == True # pylint: disable=singleton-comparison Users.superuser == True # pylint: disable=singleton-comparison
) )
for role in server_roles: 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: for user in users:
if user.user_id.user_id not in final_users: if user.user_id.user_id not in final_users:
final_users.append(user.user_id.user_id) final_users.append(user.user_id.user_id)
@ -226,36 +222,36 @@ class Permissions_Servers:
@staticmethod @staticmethod
def get_user_id_permissions_list(user_id, server_id: str): def get_user_id_permissions_list(user_id, server_id: str):
user = helper_users.get_user_model(user_id) user = HelperUsers.get_user_model(user_id)
return Permissions_Servers.get_user_permissions_list(user, server_id) return PermissionsServers.get_user_permissions_list(user, server_id)
@staticmethod @staticmethod
def get_user_permissions_list(user: Users, server_id: str): def get_user_permissions_list(user: Users, server_id: str):
if user.superuser: if user.superuser:
permissions_list = Permissions_Servers.get_permissions_list() permissions_list = PermissionsServers.get_permissions_list()
else: else:
permissions_mask = Permissions_Servers.get_user_permissions_mask( permissions_mask = PermissionsServers.get_user_permissions_mask(
user, server_id user, server_id
) )
permissions_list = Permissions_Servers.get_permissions(permissions_mask) permissions_list = PermissionsServers.get_permissions(permissions_mask)
return permissions_list return permissions_list
@staticmethod @staticmethod
def get_api_key_id_permissions_list(key_id, server_id: str): def get_api_key_id_permissions_list(key_id, server_id: str):
key = ApiKeys.get(ApiKeys.token_id == key_id) 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 @staticmethod
def get_api_key_permissions_list(key: ApiKeys, server_id: str): 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: if user["superuser"] and key.superuser:
return Permissions_Servers.get_permissions_list() return PermissionsServers.get_permissions_list()
else: 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_server = (
Role_Servers.select() RoleServers.select()
.where(Role_Servers.role_id.in_(roles_list)) .where(RoleServers.role_id.in_(roles_list))
.where(Role_Servers.server_id == server_id) .where(RoleServers.server_id == server_id)
.execute() .execute()
) )
try: try:
@ -269,5 +265,5 @@ class Permissions_Servers:
permissions_mask = PermissionHelper.combine_masks( permissions_mask = PermissionHelper.combine_masks(
user_permissions_mask, key_permissions_mask user_permissions_mask, key_permissions_mask
) )
permissions_list = Permissions_Servers.get_permissions(permissions_mask) permissions_list = PermissionsServers.get_permissions(permissions_mask)
return permissions_list return permissions_list

View File

@ -10,7 +10,7 @@ from peewee import (
FloatField, 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 from app.classes.models.base_model import BaseModel
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -45,7 +45,7 @@ class Servers(BaseModel):
# ********************************************************************************** # **********************************************************************************
# Servers Stats Class # Servers Stats Class
# ********************************************************************************** # **********************************************************************************
class Server_Stats(BaseModel): class ServerStats(BaseModel):
stats_id = AutoField() stats_id = AutoField()
created = DateTimeField(default=datetime.datetime.now) created = DateTimeField(default=datetime.datetime.now)
server_id = ForeignKeyField(Servers, backref="server", index=True) server_id = ForeignKeyField(Servers, backref="server", index=True)
@ -76,7 +76,7 @@ class Server_Stats(BaseModel):
# ********************************************************************************** # **********************************************************************************
# Servers Class # Servers Class
# ********************************************************************************** # **********************************************************************************
class helper_servers: class HelperServers:
def __init__(self, database): def __init__(self, database):
self.database = database self.database = database
@ -135,7 +135,7 @@ class helper_servers:
def get_server_data_by_id(server_id): def get_server_data_by_id(server_id):
query = Servers.select().where(Servers.server_id == server_id).limit(1) query = Servers.select().where(Servers.server_id == server_id).limit(1)
try: try:
return db_shortcuts.return_rows(query)[0] return DatabaseShortcuts.return_rows(query)[0]
except IndexError: except IndexError:
return {} return {}
@ -145,24 +145,24 @@ class helper_servers:
@staticmethod @staticmethod
def get_all_defined_servers(): def get_all_defined_servers():
query = Servers.select() query = Servers.select()
return db_shortcuts.return_rows(query) return DatabaseShortcuts.return_rows(query)
@staticmethod @staticmethod
def get_all_servers_stats(): def get_all_servers_stats():
servers = helper_servers.get_all_defined_servers() servers = HelperServers.get_all_defined_servers()
server_data = [] server_data = []
try: try:
for s in servers: for s in servers:
latest = ( latest = (
Server_Stats.select() ServerStats.select()
.where(Server_Stats.server_id == s.get("server_id")) .where(ServerStats.server_id == s.get("server_id"))
.order_by(Server_Stats.created.desc()) .order_by(ServerStats.created.desc())
.limit(1) .limit(1)
) )
server_data.append( server_data.append(
{ {
"server_data": s, "server_data": s,
"stats": db_shortcuts.return_rows(latest)[0], "stats": DatabaseShortcuts.return_rows(latest)[0],
"user_command_permission": True, "user_command_permission": True,
} }
) )
@ -174,7 +174,7 @@ class helper_servers:
@staticmethod @staticmethod
def get_server_friendly_name(server_id): 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 = ( friendly_name = (
f"{server_data.get('server_name', None)} " f"{server_data.get('server_name', None)} "
f"with ID: {server_data.get('server_id', 0)}" f"with ID: {server_data.get('server_id', 0)}"
@ -187,62 +187,62 @@ class helper_servers:
@staticmethod @staticmethod
def get_latest_server_stats(server_id): def get_latest_server_stats(server_id):
return ( return (
Server_Stats.select() ServerStats.select()
.where(Server_Stats.server_id == server_id) .where(ServerStats.server_id == server_id)
.order_by(Server_Stats.created.desc()) .order_by(ServerStats.created.desc())
.limit(1) .limit(1)
) )
@staticmethod @staticmethod
def get_server_stats_by_id(server_id): def get_server_stats_by_id(server_id):
stats = ( stats = (
Server_Stats.select() ServerStats.select()
.where(Server_Stats.server_id == server_id) .where(ServerStats.server_id == server_id)
.order_by(Server_Stats.created.desc()) .order_by(ServerStats.created.desc())
.limit(1) .limit(1)
) )
return db_shortcuts.return_rows(stats)[0] return DatabaseShortcuts.return_rows(stats)[0]
@staticmethod @staticmethod
def server_id_exists(server_id): 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 False
return True return True
@staticmethod @staticmethod
def sever_crashed(server_id): def sever_crashed(server_id):
Server_Stats.update(crashed=True).where( ServerStats.update(crashed=True).where(
Server_Stats.server_id == server_id ServerStats.server_id == server_id
).execute() ).execute()
@staticmethod @staticmethod
def set_download(server_id): def set_download(server_id):
Server_Stats.update(downloading=True).where( ServerStats.update(downloading=True).where(
Server_Stats.server_id == server_id ServerStats.server_id == server_id
).execute() ).execute()
@staticmethod @staticmethod
def finish_download(server_id): def finish_download(server_id):
Server_Stats.update(downloading=False).where( ServerStats.update(downloading=False).where(
Server_Stats.server_id == server_id ServerStats.server_id == server_id
).execute() ).execute()
@staticmethod @staticmethod
def get_download_status(server_id): def get_download_status(server_id):
download_status = ( 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 return download_status.downloading
@staticmethod @staticmethod
def server_crash_reset(server_id): def server_crash_reset(server_id):
Server_Stats.update(crashed=False).where( ServerStats.update(crashed=False).where(
Server_Stats.server_id == server_id ServerStats.server_id == server_id
).execute() ).execute()
@staticmethod @staticmethod
def is_crashed(server_id): 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: if svr.crashed is True:
return True return True
else: else:
@ -252,17 +252,17 @@ class helper_servers:
def set_update(server_id, value): def set_update(server_id, value):
try: try:
# Checks if server even exists # 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: except Exception as ex:
logger.error(f"Database entry not found! {ex}") logger.error(f"Database entry not found! {ex}")
Server_Stats.update(updating=value).where( ServerStats.update(updating=value).where(
Server_Stats.server_id == server_id ServerStats.server_id == server_id
).execute() ).execute()
@staticmethod @staticmethod
def get_update_status(server_id): def get_update_status(server_id):
update_status = ( 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 return update_status.updating
@ -271,34 +271,32 @@ class helper_servers:
# Sets first run to false # Sets first run to false
try: try:
# Checks if server even exists # 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: except Exception as ex:
logger.error(f"Database entry not found! {ex}") logger.error(f"Database entry not found! {ex}")
return return
Server_Stats.update(first_run=False).where( ServerStats.update(first_run=False).where(
Server_Stats.server_id == server_id ServerStats.server_id == server_id
).execute() ).execute()
@staticmethod @staticmethod
def get_first_run(server_id): def get_first_run(server_id):
first_run = ( first_run = ServerStats.select().where(ServerStats.server_id == server_id).get()
Server_Stats.select().where(Server_Stats.server_id == server_id).get()
)
return first_run.first_run return first_run.first_run
@staticmethod @staticmethod
def get_TTL_without_player(server_id): def get_ttl_without_player(server_id):
last_stat = ( last_stat = (
Server_Stats.select() ServerStats.select()
.where(Server_Stats.server_id == server_id) .where(ServerStats.server_id == server_id)
.order_by(Server_Stats.created.desc()) .order_by(ServerStats.created.desc())
.first() .first()
) )
last_stat_with_player = ( last_stat_with_player = (
Server_Stats.select() ServerStats.select()
.where(Server_Stats.server_id == server_id) .where(ServerStats.server_id == server_id)
.where(Server_Stats.online > 0) .where(ServerStats.online > 0)
.order_by(Server_Stats.created.desc()) .order_by(ServerStats.created.desc())
.first() .first()
) )
return last_stat.created - last_stat_with_player.created return last_stat.created - last_stat_with_player.created
@ -306,7 +304,7 @@ class helper_servers:
@staticmethod @staticmethod
def can_stop_no_players(server_id, time_limit): def can_stop_no_players(server_id, time_limit):
can = False 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): if (time_limit == -1) or (ttl_no_players > time_limit):
can = True can = True
return can return can
@ -315,16 +313,16 @@ class helper_servers:
def set_waiting_start(server_id, value): def set_waiting_start(server_id, value):
try: try:
# Checks if server even exists # 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: except Exception as ex:
logger.error(f"Database entry not found! {ex}") logger.error(f"Database entry not found! {ex}")
Server_Stats.update(waiting_start=value).where( ServerStats.update(waiting_start=value).where(
Server_Stats.server_id == server_id ServerStats.server_id == server_id
).execute() ).execute()
@staticmethod @staticmethod
def get_waiting_start(server_id): def get_waiting_start(server_id):
waiting_start = ( 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 return waiting_start.waiting_start

View File

@ -16,7 +16,7 @@ from playhouse.shortcuts import model_to_dict
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
from app.classes.models.base_model import BaseModel 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__) logger = logging.getLogger(__name__)
@ -64,7 +64,7 @@ class ApiKeys(BaseModel):
# ********************************************************************************** # **********************************************************************************
# User Roles Class # User Roles Class
# ********************************************************************************** # **********************************************************************************
class User_Roles(BaseModel): class UserRoles(BaseModel):
user_id = ForeignKeyField(Users, backref="user_role") user_id = ForeignKeyField(Users, backref="user_role")
role_id = ForeignKeyField(Roles, backref="user_role") role_id = ForeignKeyField(Roles, backref="user_role")
@ -76,7 +76,7 @@ class User_Roles(BaseModel):
# ********************************************************************************** # **********************************************************************************
# Users Helpers # Users Helpers
# ********************************************************************************** # **********************************************************************************
class helper_users: class HelperUsers:
def __init__(self, database, helper): def __init__(self, database, helper):
self.database = database self.database = database
self.helper = helper self.helper = helper
@ -128,7 +128,7 @@ class helper_users:
if user: if user:
# I know it should apply it without setting it but I'm just making sure # 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 return user
else: else:
# logger.debug("user: ({}) {}".format(user_id, {})) # logger.debug("user: ({}) {}".format(user_id, {}))
@ -146,7 +146,7 @@ class helper_users:
@staticmethod @staticmethod
def get_user_model(user_id: str) -> Users: def get_user_model(user_id: str) -> Users:
user = Users.get(Users.user_id == user_id) user = Users.get(Users.user_id == user_id)
user = helper_users.add_user_roles(user) user = HelperUsers.add_user_roles(user)
return user return user
def add_user( def add_user(
@ -223,7 +223,7 @@ class helper_users:
def remove_user(self, user_id): def remove_user(self, user_id):
with self.database.atomic(): 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) user = Users.get(Users.user_id == user_id)
return user.delete_instance() return user.delete_instance()
@ -249,7 +249,7 @@ class helper_users:
@staticmethod @staticmethod
def user_id_exists(user_id): def user_id_exists(user_id):
if not helper_users.get_user(user_id): if not HelperUsers.get_user(user_id):
return False return False
return True return True
@ -259,28 +259,28 @@ class helper_users:
@staticmethod @staticmethod
def get_or_create(user_id, role_id): 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 @staticmethod
def get_user_roles_id(user_id): def get_user_roles_id(user_id):
roles_list = [] 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: 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 return roles_list
@staticmethod @staticmethod
def get_user_roles_names(user_id): def get_user_roles_names(user_id):
roles_list = [] 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: 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 return roles_list
@staticmethod @staticmethod
def add_role_to_user(user_id, role_id): def add_role_to_user(user_id, role_id):
User_Roles.insert( UserRoles.insert(
{User_Roles.user_id: user_id, User_Roles.role_id: role_id} {UserRoles.user_id: user_id, UserRoles.role_id: role_id}
).execute() ).execute()
@staticmethod @staticmethod
@ -294,9 +294,9 @@ class helper_users:
# it had those TODOs & comments made by mac - Lukas # it had those TODOs & comments made by mac - Lukas
roles_query = ( roles_query = (
User_Roles.select() UserRoles.select()
.join(Roles, JOIN.INNER) .join(Roles, JOIN.INNER)
.where(User_Roles.user_id == user_id) .where(UserRoles.user_id == user_id)
) )
# TODO: this query needs to be narrower # TODO: this query needs to be narrower
roles = set() roles = set()
@ -313,21 +313,21 @@ class helper_users:
@staticmethod @staticmethod
def user_role_query(user_id): 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) query = Roles.select().where(Roles.role_id == -1)
for u in user_query: for user in user_query:
query = query + Roles.select().where(Roles.role_id == u.role_id) query = query + Roles.select().where(Roles.role_id == user.role_id)
return query return query
@staticmethod @staticmethod
def delete_user_roles(user_id, removed_roles): def delete_user_roles(user_id, removed_roles):
User_Roles.delete().where(User_Roles.user_id == user_id).where( UserRoles.delete().where(UserRoles.user_id == user_id).where(
User_Roles.role_id.in_(removed_roles) UserRoles.role_id.in_(removed_roles)
).execute() ).execute()
@staticmethod @staticmethod
def remove_roles_from_role_id(role_id): 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 # ApiKeys Methods

View File

@ -4,7 +4,7 @@ from typing import Optional, Dict, Any, Tuple
import jwt import jwt
from jwt import PyJWTError 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__) logger = logging.getLogger(__name__)
@ -52,11 +52,11 @@ class Authentication:
key: Optional[ApiKeys] = None key: Optional[ApiKeys] = None
if "token_id" in data: if "token_id" in data:
key_id = data["token_id"] 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: if key is None:
return None return None
user_id: str = data["user_id"] 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 # TODO: Have a cache or something so we don't constantly
# have to query the database # have to query the database
if int(user.get("valid_tokens_from").timestamp()) < iat: if int(user.get("valid_tokens_from").timestamp()) < iat:

View File

@ -5,7 +5,7 @@ import threading
import logging import logging
from app.classes.shared.console import Console 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__) logger = logging.getLogger(__name__)
@ -61,7 +61,7 @@ class MainPrompt(cmd.Cmd):
print(f"Name: {thread.name} Identifier: {thread.ident}") print(f"Name: {thread.name} Identifier: {thread.ident}")
def do_import3(self, _line): def do_import3(self, _line):
import3.start_import() Import3.start_import()
def universal_exit(self): def universal_exit(self):
logger.info("Stopping all server daemons / threads") logger.info("Stopping all server daemons / threads")

View File

@ -54,30 +54,30 @@ class Console:
@staticmethod @staticmethod
def debug(message): def debug(message):
dt = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p")
Console.magenta(f"[+] Crafty: {dt} - DEBUG:\t{message}") Console.magenta(f"[+] Crafty: {date_time} - DEBUG:\t{message}")
@staticmethod @staticmethod
def info(message): def info(message):
dt = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p")
Console.white(f"[+] Crafty: {dt} - INFO:\t{message}") Console.white(f"[+] Crafty: {date_time} - INFO:\t{message}")
@staticmethod @staticmethod
def warning(message): def warning(message):
dt = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p")
Console.cyan(f"[+] Crafty: {dt} - WARNING:\t{message}") Console.cyan(f"[+] Crafty: {date_time} - WARNING:\t{message}")
@staticmethod @staticmethod
def error(message): def error(message):
dt = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p")
Console.yellow(f"[+] Crafty: {dt} - ERROR:\t{message}") Console.yellow(f"[+] Crafty: {date_time} - ERROR:\t{message}")
@staticmethod @staticmethod
def critical(message): def critical(message):
dt = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p")
Console.red(f"[+] Crafty: {dt} - CRITICAL:\t{message}") Console.red(f"[+] Crafty: {date_time} - CRITICAL:\t{message}")
@staticmethod @staticmethod
def help(message): def help(message):
dt = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p") date_time = datetime.datetime.now().strftime("%Y-%m-%d %I:%M:%S %p")
Console.green(f"[+] Crafty: {dt} - HELP:\t{message}") Console.green(f"[+] Crafty: {date_time} - HELP:\t{message}")

View File

@ -60,19 +60,19 @@ class FileHelpers:
def make_archive(path_to_destination, path_to_zip): def make_archive(path_to_destination, path_to_zip):
# create a ZipFile object # create a ZipFile object
path_to_destination += ".zip" 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): for root, _dirs, files in os.walk(path_to_zip, topdown=True):
ziproot = path_to_zip ziproot = path_to_zip
for file in files: for file in files:
try: try:
logger.info(f"backing up: {os.path.join(root, file)}") logger.info(f"backing up: {os.path.join(root, file)}")
if os.name == "nt": if os.name == "nt":
z.write( zip_file.write(
os.path.join(root, file), os.path.join(root, file),
os.path.join(root.replace(ziproot, ""), file), os.path.join(root.replace(ziproot, ""), file),
) )
else: else:
z.write( zip_file.write(
os.path.join(root, file), os.path.join(root, file),
os.path.join(root.replace(ziproot, "/"), file), os.path.join(root.replace(ziproot, "/"), file),
) )
@ -89,19 +89,19 @@ class FileHelpers:
def make_compressed_archive(path_to_destination, path_to_zip): def make_compressed_archive(path_to_destination, path_to_zip):
# create a ZipFile object # create a ZipFile object
path_to_destination += ".zip" 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): for root, _dirs, files in os.walk(path_to_zip, topdown=True):
ziproot = path_to_zip ziproot = path_to_zip
for file in files: for file in files:
try: try:
logger.info(f"backing up: {os.path.join(root, file)}") logger.info(f"backing up: {os.path.join(root, file)}")
if os.name == "nt": if os.name == "nt":
z.write( zip_file.write(
os.path.join(root, file), os.path.join(root, file),
os.path.join(root.replace(ziproot, ""), file), os.path.join(root.replace(ziproot, ""), file),
) )
else: else:
z.write( zip_file.write(
os.path.join(root, file), os.path.join(root, file),
os.path.join(root.replace(ziproot, "/"), file), os.path.join(root.replace(ziproot, "/"), file),
) )

View File

@ -146,47 +146,51 @@ class Helpers:
def cmdparse(cmd_in): def cmdparse(cmd_in):
# Parse a string into arguments # Parse a string into arguments
cmd_out = [] # "argv" output array cmd_out = [] # "argv" output array
ci = -1 # command index - pointer to the argument we're building in cmd_out cmd_index = (
np = True # whether we're creating a new argument/parameter -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 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 # Nested quotes to be dealt with by the command
for c in cmd_in: # for character in string for char in cmd_in: # for character in string
if np: # if set, begin a new argument and increment the command index. if (
new_param
): # if set, begin a new argument and increment the command index.
# Continue the loop. # Continue the loop.
if c == " ": if char == " ":
continue continue
else: else:
ci += 1 cmd_index += 1
cmd_out.append("") cmd_out.append("")
np = False new_param = False
if esc: # if we encountered an escape character on the last loop, if esc: # if we encountered an escape character on the last loop,
# append this char regardless of what it is # append this char regardless of what it is
if c not in Helpers.allowed_quotes: if char not in Helpers.allowed_quotes:
cmd_out[ci] += "\\" cmd_out[cmd_index] += "\\"
cmd_out[ci] += c cmd_out[cmd_index] += char
esc = False esc = False
else: 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 # set the esc flag and continue to next loop
esc = True esc = True
elif ( elif (
c == " " and stch is None char == " " and quote_char is None
): # if we encounter a space and are not dealing with a quote, ): # if we encounter a space and are not dealing with a quote,
# set the new argument flag and continue to next loop # set the new argument flag and continue to next loop
np = True new_param = True
elif ( elif (
c == stch char == quote_char
): # if we encounter the character that matches our start quote, ): # if we encounter the character that matches our start quote,
# end the quote and continue to next loop # end the quote and continue to next loop
stch = None quote_char = None
elif stch is None and ( elif quote_char is None and (
c in Helpers.allowed_quotes char in Helpers.allowed_quotes
): # if we're not in the middle of a quote and we get a quotable ): # 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 # 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 else: # else, just store the character in the current arg
cmd_out[ci] += c cmd_out[cmd_index] += char
return cmd_out return cmd_out
def get_setting(self, key, default_return=False): def get_setting(self, key, default_return=False):
@ -244,12 +248,12 @@ class Helpers:
try: try:
# doesn't even have to be reachable # doesn't even have to be reachable
s.connect(("10.255.255.255", 1)) s.connect(("10.255.255.255", 1))
IP = s.getsockname()[0] ip = s.getsockname()[0]
except Exception: except Exception:
IP = "127.0.0.1" ip = "127.0.0.1"
finally: finally:
s.close() s.close()
return IP return ip
def get_version(self): def get_version(self):
version_data = {} version_data = {}
@ -266,16 +270,16 @@ class Helpers:
@staticmethod @staticmethod
def get_announcements(): def get_announcements():
r = requests.get("https://craftycontrol.com/notify.json", timeout=2) response = requests.get("https://craftycontrol.com/notify.json", timeout=2)
data = ( data = (
'[{"id":"1","date":"Unknown",' '[{"id":"1","date":"Unknown",'
'"title":"Error getting Announcements",' '"title":"Error getting Announcements",'
'"desc":"Error getting Announcements","link":""}]' '"desc":"Error getting Announcements","link":""}]'
) )
if r.status_code in [200, 201]: if response.status_code in [200, 201]:
try: try:
data = json.loads(r.content) data = json.loads(response.content)
except Exception as e: except Exception as e:
logger.error(f"Failed to load json content with error: {e}") logger.error(f"Failed to load json content with error: {e}")
@ -344,8 +348,8 @@ class Helpers:
base = pathlib.Path(base_path).resolve() base = pathlib.Path(base_path).resolve()
file = pathlib.Path(filename) file = pathlib.Path(filename)
fileabs = base.joinpath(file).resolve() fileabs = base.joinpath(file).resolve()
cp = pathlib.Path(os.path.commonpath([base, fileabs])) common_path = pathlib.Path(os.path.commonpath([base, fileabs]))
if base == cp: if base == common_path:
return fileabs return fileabs
else: else:
raise ValueError("Path traversal detected") raise ValueError("Path traversal detected")
@ -402,7 +406,7 @@ class Helpers:
return False return False
@staticmethod @staticmethod
def checkRoot(): def check_root():
if Helpers.is_os_windows(): if Helpers.is_os_windows():
if ctypes.windll.shell32.IsUserAnAdmin() == 1: if ctypes.windll.shell32.IsUserAnAdmin() == 1:
return True return True
@ -415,7 +419,7 @@ class Helpers:
return False return False
@staticmethod @staticmethod
def unzipFile(zip_path): def unzip_file(zip_path):
new_dir_list = zip_path.split("/") new_dir_list = zip_path.split("/")
new_dir = "" new_dir = ""
for i in range(len(new_dir_list) - 1): for i in range(len(new_dir_list) - 1):
@ -426,26 +430,37 @@ class Helpers:
if Helpers.check_file_perms(zip_path) and os.path.isfile(zip_path): if Helpers.check_file_perms(zip_path) and os.path.isfile(zip_path):
Helpers.ensure_dir_exists(new_dir) Helpers.ensure_dir_exists(new_dir)
tempDir = tempfile.mkdtemp() temp_dir = tempfile.mkdtemp()
try: try:
with zipfile.ZipFile(zip_path, "r") as zip_ref: 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): for i in enumerate(zip_ref.filelist):
if len(zip_ref.filelist) > 1 or not zip_ref.filelist[ if len(zip_ref.filelist) > 1 or not zip_ref.filelist[
i i
].filename.endswith("/"): ].filename.endswith("/"):
break break
full_root_path = tempDir full_root_path = temp_dir
for item in os.listdir(full_root_path): for item in os.listdir(full_root_path):
try: print(item)
FileHelpers.move_dir( if os.path.isdir(os.path.join(full_root_path, item)):
os.path.join(full_root_path, item), print("dir")
os.path.join(new_dir, item), try:
) FileHelpers.move_dir(
except Exception as ex: os.path.join(full_root_path, item),
logger.error(f"ERROR IN ZIP IMPORT: {ex}") 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: except Exception as ex:
print(ex) print(ex)
else: else:
@ -497,9 +512,9 @@ class Helpers:
source_size = 0 source_size = 0
files_count = 0 files_count = 0
for path, _dirs, files in os.walk(source_path): for path, _dirs, files in os.walk(source_path):
for f in files: for file in files:
fp = os.path.join(path, f) full_path = os.path.join(path, file)
source_size += os.stat(fp).st_size source_size += os.stat(full_path).st_size
files_count += 1 files_count += 1
dest_size = os.path.getsize(str(dest_path)) dest_size = os.path.getsize(str(dest_path))
percent = round((dest_size / source_size) * 100, 1) percent = round((dest_size / source_size) * 100, 1)
@ -719,11 +734,13 @@ class Helpers:
"DNS:127.0.0.1", "DNS:127.0.0.1",
] ]
).encode() ).encode()
subjectAltNames_Ext = crypto.X509Extension(b"subjectAltName", False, alt_names) subject_alt_names_ext = crypto.X509Extension(
basicConstraints_Ext = crypto.X509Extension( b"subjectAltName", False, alt_names
)
basic_constraints_ext = crypto.X509Extension(
b"basicConstraints", True, b"CA:false" 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.set_serial_number(random.randint(1, 255))
cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notBefore(0)
cert.gmtime_adj_notAfter(365 * 24 * 60 * 60) cert.gmtime_adj_notAfter(365 * 24 * 60 * 60)
@ -903,15 +920,15 @@ class Helpers:
</input></div><li>""" </input></div><li>"""
return output return output
def unzipServer(self, zip_path, user_id): def unzip_server(self, zip_path, user_id):
if Helpers.check_file_perms(zip_path): if Helpers.check_file_perms(zip_path):
tempDir = tempfile.mkdtemp() temp_dir = tempfile.mkdtemp()
with zipfile.ZipFile(zip_path, "r") as zip_ref: with zipfile.ZipFile(zip_path, "r") as zip_ref:
# extracts archive to temp directory # extracts archive to temp directory
zip_ref.extractall(tempDir) zip_ref.extractall(temp_dir)
if user_id: if user_id:
self.websocket_helper.broadcast_user( 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): def backup_select(self, path, user_id):
@ -924,11 +941,11 @@ class Helpers:
def unzip_backup_archive(backup_path, zip_name): def unzip_backup_archive(backup_path, zip_name):
zip_path = os.path.join(backup_path, zip_name) zip_path = os.path.join(backup_path, zip_name)
if Helpers.check_file_perms(zip_path): if Helpers.check_file_perms(zip_path):
tempDir = tempfile.mkdtemp() temp_dir = tempfile.mkdtemp()
with zipfile.ZipFile(zip_path, "r") as zip_ref: with zipfile.ZipFile(zip_path, "r") as zip_ref:
# extracts archive to temp directory # extracts archive to temp directory
zip_ref.extractall(tempDir) zip_ref.extractall(temp_dir)
return tempDir return temp_dir
else: else:
return False return False
@ -948,10 +965,6 @@ class Helpers:
[parent_path, child_path] [parent_path, child_path]
) )
@staticmethod
def in_path_old(x, y):
return os.path.abspath(y).__contains__(os.path.abspath(x))
@staticmethod @staticmethod
def copy_files(source, dest): def copy_files(source, dest):
if os.path.isfile(source): if os.path.isfile(source):
@ -963,16 +976,16 @@ class Helpers:
@staticmethod @staticmethod
def download_file(executable_url, jar_path): def download_file(executable_url, jar_path):
try: try:
r = requests.get(executable_url, timeout=5) response = requests.get(executable_url, timeout=5)
except Exception as ex: except Exception as ex:
logger.error("Could not download executable: %s", ex) logger.error("Could not download executable: %s", ex)
return False return False
if r.status_code != 200: if response.status_code != 200:
logger.error("Unable to download file from %s", executable_url) logger.error("Unable to download file from %s", executable_url)
return False return False
try: try:
open(jar_path, "wb").write(r.content) open(jar_path, "wb").write(response.content)
except Exception as e: except Exception as e:
logger.error("Unable to finish executable download. Error: %s", e) logger.error("Unable to finish executable download. Error: %s", e)
return False return False
@ -985,7 +998,7 @@ class Helpers:
return text return text
@staticmethod @staticmethod
def getLangPage(text): def get_lang_page(text):
lang = text.split("_")[0] lang = text.split("_")[0]
region = text.split("_")[1] region = text.split("_")[1]
if region == "EN": if region == "EN":

View File

@ -2,13 +2,13 @@ import json
import os import os
import logging 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 from app.classes.shared.console import Console
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class import3: class Import3:
def __init__(self, helper, controller): def __init__(self, helper, controller):
self.helper = helper self.helper = helper
self.controller = controller 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 there is only one user to import json needs to call the data differently
if isinstance(json_data, list): if isinstance(json_data, list):
for user in json_data: 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") Console.info(f"Imported user {user['username']} from Crafty 3")
logger.info(f"Imported user {user['username']} from Crafty 3") logger.info(f"Imported user {user['username']} from Crafty 3")
else: else:

View File

@ -2,7 +2,7 @@ import sys
import subprocess import subprocess
class install: class Install:
@staticmethod @staticmethod
def is_venv(): def is_venv():
return hasattr(sys, "real_prefix") or ( return hasattr(sys, "real_prefix") or (
@ -24,4 +24,4 @@ class install:
sys.exit(0) sys.exit(0)
installer = install() installer = Install()

View File

@ -12,17 +12,17 @@ from peewee import DoesNotExist
from tzlocal import get_localzone from tzlocal import get_localzone
from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.schedulers.background import BackgroundScheduler
from app.classes.controllers.crafty_perms_controller import Crafty_Perms_Controller from app.classes.controllers.crafty_perms_controller import CraftyPermsController
from app.classes.controllers.management_controller import Management_Controller from app.classes.controllers.management_controller import ManagementController
from app.classes.controllers.users_controller import Users_Controller from app.classes.controllers.users_controller import UsersController
from app.classes.controllers.roles_controller import Roles_Controller from app.classes.controllers.roles_controller import RolesController
from app.classes.controllers.server_perms_controller import Server_Perms_Controller from app.classes.controllers.server_perms_controller import ServerPermsController
from app.classes.controllers.servers_controller import Servers_Controller from app.classes.controllers.servers_controller import ServersController
from app.classes.models.server_permissions import Enum_Permissions_Server from app.classes.models.server_permissions import EnumPermissionsServer
from app.classes.models.users import helper_users from app.classes.models.users import HelperUsers
from app.classes.models.roles import helper_roles from app.classes.models.roles import HelperRoles
from app.classes.models.management import helpers_management from app.classes.models.management import HelpersManagement
from app.classes.models.servers import helper_servers from app.classes.models.servers import HelperServers
from app.classes.shared.authentication import Authentication from app.classes.shared.authentication import Authentication
from app.classes.shared.console import Console from app.classes.shared.console import Console
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
@ -39,19 +39,19 @@ class Controller:
def __init__(self, database, helper): def __init__(self, database, helper):
self.helper = helper self.helper = helper
self.server_jars = ServerJars(helper) self.server_jars = ServerJars(helper)
self.users_helper = helper_users(database, self.helper) self.users_helper = HelperUsers(database, self.helper)
self.roles_helper = helper_roles(database) self.roles_helper = HelperRoles(database)
self.servers_helper = helper_servers(database) self.servers_helper = HelperServers(database)
self.management_helper = helpers_management(database, self.helper) self.management_helper = HelpersManagement(database, self.helper)
self.authentication = Authentication(self.helper) self.authentication = Authentication(self.helper)
self.servers_list = [] self.servers_list = []
self.stats = Stats(self.helper, self) self.stats = Stats(self.helper, self)
self.crafty_perms = Crafty_Perms_Controller() self.crafty_perms = CraftyPermsController()
self.management = Management_Controller(self.management_helper) self.management = ManagementController(self.management_helper)
self.roles = Roles_Controller(self.users_helper, self.roles_helper) self.roles = RolesController(self.users_helper, self.roles_helper)
self.server_perms = Server_Perms_Controller() self.server_perms = ServerPermsController()
self.servers = Servers_Controller(self.servers_helper) self.servers = ServersController(self.servers_helper)
self.users = Users_Controller( self.users = UsersController(
self.helper, self.users_helper, self.authentication self.helper, self.users_helper, self.authentication
) )
tz = get_localzone() tz = get_localzone()
@ -62,8 +62,8 @@ class Controller:
logger.info(f"Checking to see if we already registered {server_id_to_check}") logger.info(f"Checking to see if we already registered {server_id_to_check}")
for s in self.servers_list: for server in self.servers_list:
known_server = s.get("server_id") known_server = server.get("server_id")
if known_server is None: if known_server is None:
return False return False
@ -80,8 +80,8 @@ class Controller:
servers = self.servers.get_all_defined_servers() servers = self.servers.get_all_defined_servers()
for s in servers: for server in servers:
server_id = s.get("server_id") server_id = server.get("server_id")
# if we have already initialized this server, let's skip it. # if we have already initialized this server, let's skip it.
if self.check_server_loaded(server_id): 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 this server path no longer exists - let's warn and bomb out
if not Helpers.check_path_exists( if not Helpers.check_path_exists(
Helpers.get_os_understandable_path(s["path"]) Helpers.get_os_understandable_path(server["path"])
): ):
logger.warning( 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" f"Skipping this server"
) )
Console.warning( 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" f"Skipping this server"
) )
continue continue
settings_file = os.path.join( 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 # if the properties file isn't there, let's warn
@ -115,28 +117,28 @@ class Controller:
settings = ServerProps(settings_file) settings = ServerProps(settings_file)
temp_server_dict = { temp_server_dict = {
"server_id": s.get("server_id"), "server_id": server.get("server_id"),
"server_data_obj": s, "server_data_obj": server,
"server_obj": Server(self.helper, self.management_helper, self.stats), "server_obj": Server(self.helper, self.management_helper, self.stats),
"server_settings": settings.props, "server_settings": settings.props,
} }
# setup the server, do the auto start and all that jazz # 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 # add this temp object to the list of init servers
self.servers_list.append(temp_server_dict) self.servers_list.append(temp_server_dict)
if s["auto_start"]: if server["auto_start"]:
self.servers.set_waiting_start(s["server_id"], True) 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( Console.info(
f"Loaded Server: ID {s['server_id']}" f"Loaded Server: ID {server['server_id']}"
+ f" | Name: {s['server_name']}" f" | Name: {server['server_name']}"
+ f" | Autostart: {s['auto_start']}" f" | Autostart: {server['auto_start']}"
+ f" | Delay: {s['auto_start_delay']} " f" | Delay: {server['auto_start_delay']}"
) )
def refresh_server_settings(self, server_id: int): def refresh_server_settings(self, server_id: int):
@ -145,7 +147,7 @@ class Controller:
@staticmethod @staticmethod
def check_system_user(): 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 return True
else: else:
return False return False
@ -162,11 +164,11 @@ class Controller:
self.helper.websocket_helper.broadcast_user( self.helper.websocket_helper.broadcast_user(
exec_user["user_id"], "notification", "Preparing your support logs" exec_user["user_id"], "notification", "Preparing your support logs"
) )
tempDir = tempfile.mkdtemp() temp_dir = tempfile.mkdtemp()
tempZipStorage = tempfile.mkdtemp() temp_zip_storage = tempfile.mkdtemp()
full_temp = os.path.join(tempDir, "support_logs") full_temp = os.path.join(temp_dir, "support_logs")
os.mkdir(full_temp) 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") crafty_path = os.path.join(full_temp, "crafty")
os.mkdir(crafty_path) os.mkdir(crafty_path)
server_path = os.path.join(full_temp, "server") server_path = os.path.join(full_temp, "server")
@ -180,7 +182,7 @@ class Controller:
auth_servers = [] auth_servers = []
for server in user_servers: for server in user_servers:
if ( if (
Enum_Permissions_Server.Logs EnumPermissionsServer.LOGS
in self.server_perms.get_user_id_permissions_list( in self.server_perms.get_user_id_permissions_list(
exec_user["user_id"], server["server_id"] exec_user["user_id"], server["server_id"]
) )
@ -211,30 +213,30 @@ class Controller:
"interval", "interval",
seconds=1, seconds=1,
id="logs_" + str(exec_user["user_id"]), 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: if len(self.helper.websocket_helper.clients) > 0:
self.helper.websocket_helper.broadcast_user( self.helper.websocket_helper.broadcast_user(
exec_user["user_id"], exec_user["user_id"],
"support_status_update", "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( self.helper.websocket_helper.broadcast_user(
exec_user["user_id"], "send_logs_bootbox", {} 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.users.stop_prepare(exec_user["user_id"])
self.support_scheduler.remove_job("logs_" + str(exec_user["user_id"])) self.support_scheduler.remove_job("logs_" + str(exec_user["user_id"]))
@staticmethod @staticmethod
def add_system_user(): def add_system_user():
helper_users.add_user( HelperUsers.add_user(
"system", "system",
Helpers.random_string_generator(64), Helpers.random_string_generator(64),
"default@example.com", "default@example.com",
@ -243,9 +245,9 @@ class Controller:
) )
def get_server_settings(self, server_id): def get_server_settings(self, server_id):
for s in self.servers_list: for server in self.servers_list:
if int(s["server_id"]) == int(server_id): if int(server["server_id"]) == int(server_id):
return s["server_settings"] return server["server_settings"]
logger.warning(f"Unable to find server object for server id {server_id}") logger.warning(f"Unable to find server object for server id {server_id}")
return False return False
@ -276,34 +278,34 @@ class Controller:
return {"percent": 0, "total_files": 0} return {"percent": 0, "total_files": 0}
def get_server_obj(self, server_id: Union[str, int]) -> Union[bool, Server]: def get_server_obj(self, server_id: Union[str, int]) -> Union[bool, Server]:
for s in self.servers_list: for server in self.servers_list:
if str(s["server_id"]) == str(server_id): if str(server["server_id"]) == str(server_id):
return s["server_obj"] return server["server_obj"]
logger.warning(f"Unable to find server object for server id {server_id}") logger.warning(f"Unable to find server object for server id {server_id}")
return False # TODO: Change to None return False # TODO: Change to None
def get_server_data(self, server_id: str): def get_server_data(self, server_id: str):
for s in self.servers_list: for server in self.servers_list:
if str(s["server_id"]) == str(server_id): if str(server["server_id"]) == str(server_id):
return s["server_data_obj"] return server["server_data_obj"]
logger.warning(f"Unable to find server object for server id {server_id}") logger.warning(f"Unable to find server object for server id {server_id}")
return False return False
@staticmethod @staticmethod
def list_defined_servers(): def list_defined_servers():
servers = helper_servers.get_all_defined_servers() servers = HelperServers.get_all_defined_servers()
return servers return servers
def list_running_servers(self): def list_running_servers(self):
running_servers = [] running_servers = []
# for each server # for each server
for s in self.servers_list: for servers in self.servers_list:
# is the server running? # is the server running?
srv_obj = s["server_obj"] srv_obj = servers["server_obj"]
running = srv_obj.check_running() running = srv_obj.check_running()
# if so, let's add a dictionary to the list of running servers # if so, let's add a dictionary to the list of running servers
if running: if running:
@ -319,11 +321,11 @@ class Controller:
logger.info("Stopping All Servers") logger.info("Stopping All Servers")
Console.info("Stopping All Servers") Console.info("Stopping All Servers")
for s in servers: for server in servers:
logger.info(f"Stopping Server ID {s['id']} - {s['name']}") logger.info(f"Stopping Server ID {server['id']} - {server['name']}")
Console.info(f"Stopping Server ID {s['id']} - {s['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 # let's wait 2 seconds to let everything flush out
time.sleep(2) time.sleep(2)
@ -363,16 +365,18 @@ class Controller:
try: try:
# do a eula.txt # do a eula.txt
with open(os.path.join(server_dir, "eula.txt"), "w", encoding="utf-8") as f: with open(
f.write("eula=false") os.path.join(server_dir, "eula.txt"), "w", encoding="utf-8"
f.close() ) as file:
file.write("eula=false")
file.close()
# setup server.properties with the port # setup server.properties with the port
with open( with open(
os.path.join(server_dir, "server.properties"), "w", encoding="utf-8" os.path.join(server_dir, "server.properties"), "w", encoding="utf-8"
) as f: ) as file:
f.write(f"server-port={port}") file.write(f"server-port={port}")
f.close() file.close()
except Exception as e: except Exception as e:
logger.error(f"Unable to create required server files due to :{e}") logger.error(f"Unable to create required server files due to :{e}")
@ -465,9 +469,9 @@ class Controller:
) )
with open( with open(
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8" os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
) as f: ) as file:
f.write(f"server-port={port}") file.write(f"server-port={port}")
f.close() file.close()
full_jar_path = os.path.join(new_server_dir, server_jar) full_jar_path = os.path.join(new_server_dir, server_jar)
@ -518,22 +522,22 @@ class Controller:
new_server_dir.replace(" ", "^ ") new_server_dir.replace(" ", "^ ")
backup_path.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(new_server_dir)
Helpers.ensure_dir_exists(backup_path) Helpers.ensure_dir_exists(backup_path)
has_properties = False has_properties = False
# extracts archive to temp directory # extracts archive to temp directory
for item in os.listdir(tempDir): for item in os.listdir(temp_dir):
if str(item) == "server.properties": if str(item) == "server.properties":
has_properties = True has_properties = True
try: 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( 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: else:
FileHelpers.move_dir( 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: except Exception as ex:
logger.error(f"ERROR IN ZIP IMPORT: {ex}") logger.error(f"ERROR IN ZIP IMPORT: {ex}")
@ -544,9 +548,9 @@ class Controller:
) )
with open( with open(
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8" os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
) as f: ) as file:
f.write(f"server-port={port}") file.write(f"server-port={port}")
f.close() file.close()
full_jar_path = os.path.join(new_server_dir, server_jar) full_jar_path = os.path.join(new_server_dir, server_jar)
@ -615,9 +619,9 @@ class Controller:
) )
with open( with open(
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8" os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
) as f: ) as file:
f.write(f"server-port={port}") file.write(f"server-port={port}")
f.close() file.close()
full_jar_path = os.path.join(new_server_dir, server_exe) full_jar_path = os.path.join(new_server_dir, server_exe)
@ -658,22 +662,22 @@ class Controller:
new_server_dir.replace(" ", "^ ") new_server_dir.replace(" ", "^ ")
backup_path.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(new_server_dir)
Helpers.ensure_dir_exists(backup_path) Helpers.ensure_dir_exists(backup_path)
has_properties = False has_properties = False
# extracts archive to temp directory # extracts archive to temp directory
for item in os.listdir(tempDir): for item in os.listdir(temp_dir):
if str(item) == "server.properties": if str(item) == "server.properties":
has_properties = True has_properties = True
try: 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( 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: else:
FileHelpers.move_dir( 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: except Exception as ex:
logger.error(f"ERROR IN ZIP IMPORT: {ex}") logger.error(f"ERROR IN ZIP IMPORT: {ex}")
@ -684,9 +688,9 @@ class Controller:
) )
with open( with open(
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8" os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
) as f: ) as file:
f.write(f"server-port={port}") file.write(f"server-port={port}")
f.close() file.close()
full_jar_path = os.path.join(new_server_dir, server_exe) 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): 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) server_data = self.servers.get_server_data_by_id(old_server_id)
old_bu_path = server_data["backup_path"] 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(): if not Helpers.is_os_windows():
backup_path = Helpers.validate_traversal( backup_path = Helpers.validate_traversal(
self.helper.backup_path, old_bu_path self.helper.backup_path, old_bu_path
@ -758,7 +762,6 @@ class Controller:
server_type: str, server_type: str,
): ):
# put data in the db # put data in the db
new_id = self.servers.create_server( new_id = self.servers.create_server(
name, name,
server_uuid, server_uuid,
@ -781,12 +784,12 @@ class Controller:
os.path.join(server_dir, "crafty_managed.txt"), os.path.join(server_dir, "crafty_managed.txt"),
"w", "w",
encoding="utf-8", encoding="utf-8",
) as f: ) as file:
f.write( file.write(
"The server is managed by Crafty Controller.\n " "The server is managed by Crafty Controller.\n "
"Leave this directory/files alone please" "Leave this directory/files alone please"
) )
f.close() file.close()
except Exception as e: except Exception as e:
logger.error(f"Unable to create required server files due to :{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): def remove_server(self, server_id, files):
counter = 0 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 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_data = self.get_server_data(server_id)
server_name = server_data["server_name"] server_name = server_data["server_name"]
logger.info(f"Deleting Server: ID {server_id} | Name: {server_name} ") logger.info(f"Deleting Server: ID {server_id} | Name: {server_name} ")
Console.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() running = srv_obj.check_running()
if running: if running:
@ -839,7 +842,7 @@ class Controller:
# Cleanup scheduled tasks # Cleanup scheduled tasks
try: try:
helpers_management.delete_scheduled_task_by_server(server_id) HelpersManagement.delete_scheduled_task_by_server(server_id)
except DoesNotExist: except DoesNotExist:
logger.info("No scheduled jobs exist. Continuing.") logger.info("No scheduled jobs exist. Continuing.")
# remove the server from the DB # remove the server from the DB
@ -852,8 +855,8 @@ class Controller:
@staticmethod @staticmethod
def clear_unexecuted_commands(): def clear_unexecuted_commands():
helpers_management.clear_unexecuted_commands() HelpersManagement.clear_unexecuted_commands()
@staticmethod @staticmethod
def clear_support_status(): def clear_support_status():
helper_users.clear_support_status() HelperUsers.clear_support_status()

View File

@ -1,13 +1,12 @@
import logging import logging
from playhouse.shortcuts import model_to_dict from playhouse.shortcuts import model_to_dict
# pylint: disable=unused-import from app.classes.shared.helpers import Helpers # pylint: disable=unused-import
from app.classes.shared.helpers import Helpers
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class db_builder: class DatabaseBuilder:
def __init__(self, database, helper, users_helper): def __init__(self, database, helper, users_helper):
self.database = database self.database = database
self.helper = helper self.helper = helper
@ -37,7 +36,7 @@ class db_builder:
return True return True
class db_shortcuts: class DatabaseShortcuts:
# ********************************************************************************** # **********************************************************************************
# Generic Databse Methods # Generic Databse Methods
# ********************************************************************************** # **********************************************************************************

View File

@ -1,483 +1,483 @@
# pylint: skip-file # pylint: skip-file
from datetime import datetime from datetime import datetime
import logging import logging
import typing as t import typing as t
import sys import sys
import os import os
import re import re
from functools import wraps from functools import wraps
from functools import cached_property from functools import cached_property
import peewee import peewee
from playhouse.migrate import ( from playhouse.migrate import (
SqliteMigrator, SqliteMigrator,
Operation, Operation,
SQL, SQL,
SqliteDatabase, SqliteDatabase,
make_index_name, make_index_name,
) )
from app.classes.shared.console import Console from app.classes.shared.console import Console
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
MIGRATE_TABLE = "migratehistory" MIGRATE_TABLE = "migratehistory"
MIGRATE_TEMPLATE = '''# Generated by database migrator MIGRATE_TEMPLATE = '''# Generated by database migrator
import peewee import peewee
def migrate(migrator, db): def migrate(migrator, db):
""" """
Write your migrations here. Write your migrations here.
""" """
{migrate} {migrate}
def rollback(migrator, db): def rollback(migrator, db):
""" """
Write your rollback migrations here. Write your rollback migrations here.
""" """
{rollback}''' {rollback}'''
class MigrateHistory(peewee.Model): class MigrateHistory(peewee.Model):
""" """
Presents the migration history in a database. Presents the migration history in a database.
""" """
name = peewee.CharField(unique=True) name = peewee.CharField(unique=True)
migrated_at = peewee.DateTimeField(default=datetime.utcnow) migrated_at = peewee.DateTimeField(default=datetime.utcnow)
# noinspection PyTypeChecker # noinspection PyTypeChecker
def __unicode__(self) -> str: def __unicode__(self) -> str:
""" """
String representation of this migration String representation of this migration
""" """
return self.name return self.name
class Meta: class Meta:
table_name = MIGRATE_TABLE table_name = MIGRATE_TABLE
def get_model(method): def get_model(method):
""" """
Convert string to model class. Convert string to model class.
""" """
@wraps(method) @wraps(method)
def wrapper(migrator, model, *args, **kwargs): def wrapper(migrator, model, *args, **kwargs):
if isinstance(model, str): if isinstance(model, str):
return method(migrator, migrator.table_dict[model], *args, **kwargs) return method(migrator, migrator.table_dict[model], *args, **kwargs)
return method(migrator, model, *args, **kwargs) return method(migrator, model, *args, **kwargs)
return wrapper return wrapper
# noinspection PyProtectedMember # noinspection PyProtectedMember
class Migrator(object): class Migrator(object):
def __init__(self, database: t.Union[peewee.Database, peewee.Proxy]): def __init__(self, database: t.Union[peewee.Database, peewee.Proxy]):
""" """
Initializes the migrator Initializes the migrator
""" """
if isinstance(database, peewee.Proxy): if isinstance(database, peewee.Proxy):
database = database.obj database = database.obj
self.database: SqliteDatabase = database self.database: SqliteDatabase = database
self.table_dict: t.Dict[str, peewee.Model] = {} self.table_dict: t.Dict[str, peewee.Model] = {}
self.operations: t.List[t.Union[Operation, callable]] = [] self.operations: t.List[t.Union[Operation, callable]] = []
self.migrator = SqliteMigrator(database) self.migrator = SqliteMigrator(database)
def run(self): def run(self):
""" """
Runs operations. Runs operations.
""" """
for op in self.operations: for op in self.operations:
if isinstance(op, Operation): if isinstance(op, Operation):
op.run() op.run()
else: else:
op() op()
self.clean() self.clean()
def clean(self): def clean(self):
""" """
Cleans the operations. Cleans the operations.
""" """
self.operations = list() self.operations = list()
def sql(self, sql: str, *params): def sql(self, sql: str, *params):
""" """
Executes raw SQL. Executes raw SQL.
""" """
self.operations.append(SQL(sql, *params)) self.operations.append(SQL(sql, *params))
def create_table(self, model: peewee.Model) -> peewee.Model: def create_table(self, model: peewee.Model) -> peewee.Model:
""" """
Creates model and table in database. Creates model and table in database.
""" """
self.table_dict[model._meta.table_name] = model self.table_dict[model._meta.table_name] = model
model._meta.database = self.database model._meta.database = self.database
self.operations.append(model.create_table) self.operations.append(model.create_table)
return model return model
@get_model @get_model
def drop_table(self, model: peewee.Model): def drop_table(self, model: peewee.Model):
""" """
Drops model and table from database. Drops model and table from database.
""" """
del self.table_dict[model._meta.table_name] del self.table_dict[model._meta.table_name]
self.operations.append(lambda: model.drop_table(cascade=False)) self.operations.append(lambda: model.drop_table(cascade=False))
@get_model @get_model
def add_columns(self, model: peewee.Model, **fields: peewee.Field) -> peewee.Model: def add_columns(self, model: peewee.Model, **fields: peewee.Field) -> peewee.Model:
""" """
Creates new fields. Creates new fields.
""" """
for name, field in fields.items(): for name, field in fields.items():
model._meta.add_field(name, field) model._meta.add_field(name, field)
self.operations.append( self.operations.append(
self.migrator.add_column( self.migrator.add_column(
model._meta.table_name, field.column_name, field model._meta.table_name, field.column_name, field
) )
) )
if field.unique: if field.unique:
self.operations.append( self.operations.append(
self.migrator.add_index( self.migrator.add_index(
model._meta.table_name, (field.column_name,), unique=True model._meta.table_name, (field.column_name,), unique=True
) )
) )
return model return model
@get_model @get_model
def drop_columns(self, model: peewee.Model, names: str) -> peewee.Model: def drop_columns(self, model: peewee.Model, names: str) -> peewee.Model:
""" """
Removes fields from model. Removes fields from model.
""" """
fields = [field for field in model._meta.fields.values() if field.name in names] fields = [field for field in model._meta.fields.values() if field.name in names]
for field in fields: for field in fields:
self.__del_field__(model, field) self.__del_field__(model, field)
if field.unique: if field.unique:
# Drop unique index # Drop unique index
index_name = make_index_name( index_name = make_index_name(
model._meta.table_name, [field.column_name] model._meta.table_name, [field.column_name]
) )
self.operations.append( self.operations.append(
self.migrator.drop_index(model._meta.table_name, index_name) self.migrator.drop_index(model._meta.table_name, index_name)
) )
self.operations.append( self.operations.append(
self.migrator.drop_column( self.migrator.drop_column(
model._meta.table_name, field.column_name, cascade=False model._meta.table_name, field.column_name, cascade=False
) )
) )
return model return model
def __del_field__(self, model: peewee.Model, field: peewee.Field): def __del_field__(self, model: peewee.Model, field: peewee.Field):
""" """
Deletes field from model. Deletes field from model.
""" """
model._meta.remove_field(field.name) model._meta.remove_field(field.name)
delattr(model, field.name) delattr(model, field.name)
if isinstance(field, peewee.ForeignKeyField): if isinstance(field, peewee.ForeignKeyField):
obj_id_name = field.column_name obj_id_name = field.column_name
if field.column_name == field.name: if field.column_name == field.name:
obj_id_name += "_id" obj_id_name += "_id"
delattr(model, obj_id_name) delattr(model, obj_id_name)
delattr(field.rel_model, field.backref) delattr(field.rel_model, field.backref)
@get_model @get_model
def rename_column( def rename_column(
self, model: peewee.Model, old_name: str, new_name: str self, model: peewee.Model, old_name: str, new_name: str
) -> peewee.Model: ) -> peewee.Model:
""" """
Renames field in model. Renames field in model.
""" """
field = model._meta.fields[old_name] field = model._meta.fields[old_name]
if isinstance(field, peewee.ForeignKeyField): if isinstance(field, peewee.ForeignKeyField):
old_name = field.column_name old_name = field.column_name
self.__del_field__(model, field) self.__del_field__(model, field)
field.name = field.column_name = new_name field.name = field.column_name = new_name
model._meta.add_field(new_name, field) model._meta.add_field(new_name, field)
if isinstance(field, peewee.ForeignKeyField): if isinstance(field, peewee.ForeignKeyField):
field.column_name = new_name = field.column_name + "_id" field.column_name = new_name = field.column_name + "_id"
self.operations.append( self.operations.append(
self.migrator.rename_column(model._meta.table_name, old_name, new_name) self.migrator.rename_column(model._meta.table_name, old_name, new_name)
) )
return model return model
@get_model @get_model
def rename_table(self, model: peewee.Model, new_name: str) -> peewee.Model: def rename_table(self, model: peewee.Model, new_name: str) -> peewee.Model:
""" """
Renames table in database. Renames table in database.
""" """
old_name = model._meta.table_name old_name = model._meta.table_name
del self.table_dict[model._meta.table_name] del self.table_dict[model._meta.table_name]
model._meta.table_name = new_name model._meta.table_name = new_name
self.table_dict[model._meta.table_name] = model self.table_dict[model._meta.table_name] = model
self.operations.append(self.migrator.rename_table(old_name, new_name)) self.operations.append(self.migrator.rename_table(old_name, new_name))
return model return model
@get_model @get_model
def add_index( def add_index(
self, model: peewee.Model, *columns: str, unique=False self, model: peewee.Model, *columns: str, unique=False
) -> peewee.Model: ) -> peewee.Model:
"""Create indexes.""" """Create indexes."""
model._meta.indexes.append((columns, unique)) model._meta.indexes.append((columns, unique))
columns_ = [] columns_ = []
for col in columns: for col in columns:
field = model._meta.fields.get(col) field = model._meta.fields.get(col)
if len(columns) == 1: if len(columns) == 1:
field.unique = unique field.unique = unique
field.index = not unique field.index = not unique
if isinstance(field, peewee.ForeignKeyField): if isinstance(field, peewee.ForeignKeyField):
col = col + "_id" col = col + "_id"
columns_.append(col) columns_.append(col)
self.operations.append( self.operations.append(
self.migrator.add_index(model._meta.table_name, columns_, unique=unique) self.migrator.add_index(model._meta.table_name, columns_, unique=unique)
) )
return model return model
@get_model @get_model
def drop_index(self, model: peewee.Model, *columns: str) -> peewee.Model: def drop_index(self, model: peewee.Model, *columns: str) -> peewee.Model:
"""Drop indexes.""" """Drop indexes."""
columns_ = [] columns_ = []
for col in columns: for col in columns:
field = model._meta.fields.get(col) field = model._meta.fields.get(col)
if not field: if not field:
continue continue
if len(columns) == 1: if len(columns) == 1:
field.unique = field.index = False field.unique = field.index = False
if isinstance(field, peewee.ForeignKeyField): if isinstance(field, peewee.ForeignKeyField):
col = col + "_id" col = col + "_id"
columns_.append(col) columns_.append(col)
index_name = make_index_name(model._meta.table_name, columns_) index_name = make_index_name(model._meta.table_name, columns_)
model._meta.indexes = [ model._meta.indexes = [
(cols, _) for (cols, _) in model._meta.indexes if columns != cols (cols, _) for (cols, _) in model._meta.indexes if columns != cols
] ]
self.operations.append( self.operations.append(
self.migrator.drop_index(model._meta.table_name, index_name) self.migrator.drop_index(model._meta.table_name, index_name)
) )
return model return model
@get_model @get_model
def add_not_null(self, model: peewee.Model, *names: str) -> peewee.Model: def add_not_null(self, model: peewee.Model, *names: str) -> peewee.Model:
"""Add not null.""" """Add not null."""
for name in names: for name in names:
field = model._meta.fields[name] field = model._meta.fields[name]
field.null = False field.null = False
self.operations.append( self.operations.append(
self.migrator.add_not_null(model._meta.table_name, field.column_name) self.migrator.add_not_null(model._meta.table_name, field.column_name)
) )
return model return model
@get_model @get_model
def drop_not_null(self, model: peewee.Model, *names: str) -> peewee.Model: def drop_not_null(self, model: peewee.Model, *names: str) -> peewee.Model:
"""Drop not null.""" """Drop not null."""
for name in names: for name in names:
field = model._meta.fields[name] field = model._meta.fields[name]
field.null = True field.null = True
self.operations.append( self.operations.append(
self.migrator.drop_not_null(model._meta.table_name, field.column_name) self.migrator.drop_not_null(model._meta.table_name, field.column_name)
) )
return model return model
@get_model @get_model
def add_default( def add_default(
self, model: peewee.Model, name: str, default: t.Any self, model: peewee.Model, name: str, default: t.Any
) -> peewee.Model: ) -> peewee.Model:
"""Add default.""" """Add default."""
field = model._meta.fields[name] field = model._meta.fields[name]
model._meta.defaults[field] = field.default = default model._meta.defaults[field] = field.default = default
self.operations.append( self.operations.append(
self.migrator.apply_default(model._meta.table_name, name, field) self.migrator.apply_default(model._meta.table_name, name, field)
) )
return model return model
# noinspection PyProtectedMember # noinspection PyProtectedMember
class MigrationManager(object): class MigrationManager(object):
filemask = re.compile(r"[\d]+_[^\.]+\.py$") filemask = re.compile(r"[\d]+_[^\.]+\.py$")
def __init__(self, database: t.Union[peewee.Database, peewee.Proxy], helper): def __init__(self, database: t.Union[peewee.Database, peewee.Proxy], helper):
""" """
Initializes the migration manager. Initializes the migration manager.
""" """
if not isinstance(database, (peewee.Database, peewee.Proxy)): if not isinstance(database, (peewee.Database, peewee.Proxy)):
raise RuntimeError("Invalid database: {}".format(database)) raise RuntimeError("Invalid database: {}".format(database))
self.database = database self.database = database
self.helper = helper self.helper = helper
@cached_property @cached_property
def model(self) -> t.Type[MigrateHistory]: def model(self) -> t.Type[MigrateHistory]:
""" """
Initialize and cache the MigrationHistory model. Initialize and cache the MigrationHistory model.
""" """
MigrateHistory._meta.database = self.database MigrateHistory._meta.database = self.database
MigrateHistory._meta.table_name = "migratehistory" MigrateHistory._meta.table_name = "migratehistory"
MigrateHistory._meta.schema = None MigrateHistory._meta.schema = None
MigrateHistory.create_table(True) MigrateHistory.create_table(True)
return MigrateHistory return MigrateHistory
@property @property
def done(self) -> t.List[str]: def done(self) -> t.List[str]:
""" """
Scans migrations in the database. Scans migrations in the database.
""" """
return [mm.name for mm in self.model.select().order_by(self.model.id)] return [mm.name for mm in self.model.select().order_by(self.model.id)]
@property @property
def todo(self): def todo(self):
""" """
Scans migrations in the file system. Scans migrations in the file system.
""" """
if not os.path.exists(self.helper.migration_dir): if not os.path.exists(self.helper.migration_dir):
logger.warning( logger.warning(
"Migration directory: {} does not exist.".format( "Migration directory: {} does not exist.".format(
self.helper.migration_dir self.helper.migration_dir
) )
) )
os.makedirs(self.helper.migration_dir) os.makedirs(self.helper.migration_dir)
return sorted( return sorted(
f[:-3] f[:-3]
for f in os.listdir(self.helper.migration_dir) for f in os.listdir(self.helper.migration_dir)
if self.filemask.match(f) if self.filemask.match(f)
) )
@property @property
def diff(self) -> t.List[str]: def diff(self) -> t.List[str]:
""" """
Calculates difference between the filesystem and the database. Calculates difference between the filesystem and the database.
""" """
done = set(self.done) done = set(self.done)
return [name for name in self.todo if name not in done] return [name for name in self.todo if name not in done]
@cached_property @cached_property
def migrator(self) -> Migrator: def migrator(self) -> Migrator:
""" """
Create migrator and setup it with fake migrations. Create migrator and setup it with fake migrations.
""" """
migrator = Migrator(self.database) migrator = Migrator(self.database)
for name in self.done: for name in self.done:
self.up_one(name, migrator, True) self.up_one(name, migrator, True)
return migrator return migrator
def compile(self, name, migrate="", rollback=""): def compile(self, name, migrate="", rollback=""):
""" """
Compiles a migration. Compiles a migration.
""" """
name = datetime.utcnow().strftime("%Y%m%d%H%M%S") + "_" + name name = datetime.utcnow().strftime("%Y%m%d%H%M%S") + "_" + name
filename = name + ".py" filename = name + ".py"
path = os.path.join(self.helper.migration_dir, filename) path = os.path.join(self.helper.migration_dir, filename)
with open(path, "w") as f: with open(path, "w") as f:
f.write( f.write(
MIGRATE_TEMPLATE.format( MIGRATE_TEMPLATE.format(
migrate=migrate, rollback=rollback, name=filename migrate=migrate, rollback=rollback, name=filename
) )
) )
return name return name
def create(self, name: str = "auto", auto: bool = False) -> t.Optional[str]: def create(self, name: str = "auto", auto: bool = False) -> t.Optional[str]:
""" """
Creates a migration. Creates a migration.
""" """
migrate = rollback = "" migrate = rollback = ""
if auto: if auto:
raise NotImplementedError raise NotImplementedError
logger.info('Creating migration "{}"'.format(name)) logger.info('Creating migration "{}"'.format(name))
name = self.compile(name, migrate, rollback) name = self.compile(name, migrate, rollback)
logger.info('Migration has been created as "{}"'.format(name)) logger.info('Migration has been created as "{}"'.format(name))
return name return name
def clear(self): def clear(self):
"""Clear migrations.""" """Clear migrations."""
self.model.delete().execute() self.model.delete().execute()
def up(self, name: t.Optional[str] = None): def up(self, name: t.Optional[str] = None):
""" """
Runs all unapplied migrations. Runs all unapplied migrations.
""" """
logger.info("Starting migrations") logger.info("Starting migrations")
Console.info("Starting migrations") Console.info("Starting migrations")
done = [] done = []
diff = self.diff diff = self.diff
if not diff: if not diff:
logger.info("There is nothing to migrate") logger.info("There is nothing to migrate")
Console.info("There is nothing to migrate") Console.info("There is nothing to migrate")
return done return done
migrator = self.migrator migrator = self.migrator
for mname in diff: for mname in diff:
done.append(self.up_one(mname, self.migrator)) done.append(self.up_one(mname, self.migrator))
if name and name == mname: if name and name == mname:
break break
return done return done
def read(self, name: str): def read(self, name: str):
""" """
Reads a migration from a file. Reads a migration from a file.
""" """
call_params = dict() call_params = dict()
if Helpers.is_os_windows() and sys.version_info >= (3, 0): if Helpers.is_os_windows() and sys.version_info >= (3, 0):
# if system is windows - force utf-8 encoding # if system is windows - force utf-8 encoding
call_params["encoding"] = "utf-8" call_params["encoding"] = "utf-8"
with open( with open(
os.path.join(self.helper.migration_dir, name + ".py"), **call_params os.path.join(self.helper.migration_dir, name + ".py"), **call_params
) as f: ) as f:
code = f.read() code = f.read()
scope = {} scope = {}
code = compile(code, "<string>", "exec", dont_inherit=True) code = compile(code, "<string>", "exec", dont_inherit=True)
exec(code, scope, None) exec(code, scope, None)
return scope.get("migrate", lambda m, d: None), scope.get( return scope.get("migrate", lambda m, d: None), scope.get(
"rollback", lambda m, d: None "rollback", lambda m, d: None
) )
def up_one( def up_one(
self, name: str, migrator: Migrator, fake: bool = False, rollback: bool = False self, name: str, migrator: Migrator, fake: bool = False, rollback: bool = False
) -> str: ) -> str:
""" """
Runs a migration with a given name. Runs a migration with a given name.
""" """
try: try:
migrate_fn, rollback_fn = self.read(name) migrate_fn, rollback_fn = self.read(name)
if fake: if fake:
migrate_fn(migrator, self.database) migrate_fn(migrator, self.database)
migrator.clean() migrator.clean()
return name return name
with self.database.transaction(): with self.database.transaction():
if rollback: if rollback:
logger.info('Rolling back "{}"'.format(name)) logger.info('Rolling back "{}"'.format(name))
rollback_fn(migrator, self.database) rollback_fn(migrator, self.database)
migrator.run() migrator.run()
self.model.delete().where(self.model.name == name).execute() self.model.delete().where(self.model.name == name).execute()
else: else:
logger.info('Migrate "{}"'.format(name)) logger.info('Migrate "{}"'.format(name))
migrate_fn(migrator, self.database) migrate_fn(migrator, self.database)
migrator.run() migrator.run()
if name not in self.done: if name not in self.done:
self.model.create(name=name) self.model.create(name=name)
logger.info('Done "{}"'.format(name)) logger.info('Done "{}"'.format(name))
return name return name
except Exception: except Exception:
self.database.rollback() self.database.rollback()
operation_name = "Rollback" if rollback else "Migration" operation_name = "Rollback" if rollback else "Migration"
logger.exception("{} failed: {}".format(operation_name, name)) logger.exception("{} failed: {}".format(operation_name, name))
raise raise
def down(self): def down(self):
""" """
Rolls back migrations. Rolls back migrations.
""" """
if not self.done: if not self.done:
raise RuntimeError("No migrations are found.") raise RuntimeError("No migrations are found.")
name = self.done[-1] name = self.done[-1]
migrator = self.migrator migrator = self.migrator
self.up_one(name, migrator, False, True) self.up_one(name, migrator, False, True)
logger.warning("Rolled back migration: {}".format(name)) logger.warning("Rolled back migration: {}".format(name))

View File

@ -3,18 +3,21 @@ from enum import Enum
class PermissionHelper: class PermissionHelper:
@staticmethod @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( 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 @staticmethod
def combine_perm(a: str, b: str) -> str: def combine_perm(permission_mask_a: str, permission_mask_b: str) -> str:
return "1" if (a == "1" and b == "1") else "0" return "1" if (permission_mask_a == "1" and permission_mask_b == "1") else "0"
@staticmethod @staticmethod
def combine_perm_bool(a: str, b: str) -> bool: def combine_perm_bool(permission_mask_a: str, permission_mask_b: str) -> bool:
return a == "1" and b == "1" return permission_mask_a == "1" and permission_mask_b == "1"
@staticmethod @staticmethod
def combine_masks(permission_mask_a: str, permission_mask_b: str) -> str: def combine_masks(permission_mask_a: str, permission_mask_b: str) -> str:

View File

@ -17,10 +17,10 @@ from apscheduler.schedulers.background import BackgroundScheduler
from app.classes.minecraft.stats import Stats from app.classes.minecraft.stats import Stats
from app.classes.minecraft.mc_ping import ping, ping_bedrock from app.classes.minecraft.mc_ping import ping, ping_bedrock
from app.classes.models.servers import Server_Stats, helper_servers from app.classes.models.servers import ServerStats, HelperServers
from app.classes.models.management import helpers_management from app.classes.models.management import HelpersManagement
from app.classes.models.users import helper_users from app.classes.models.users import HelperUsers
from app.classes.models.server_permissions import Permissions_Servers from app.classes.models.server_permissions import PermissionsServers
from app.classes.shared.console import Console from app.classes.shared.console import Console
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
from app.classes.shared.file_helpers import FileHelpers from app.classes.shared.file_helpers import FileHelpers
@ -118,28 +118,28 @@ class Server:
) )
self.is_backingup = False self.is_backingup = False
# Reset crash and update at initialization # Reset crash and update at initialization
helper_servers.server_crash_reset(self.server_id) HelperServers.server_crash_reset(self.server_id)
helper_servers.set_update(self.server_id, False) HelperServers.set_update(self.server_id, False)
# ********************************************************************************** # **********************************************************************************
# Minecraft Server Management # Minecraft Server Management
# ********************************************************************************** # **********************************************************************************
def reload_server_settings(self): 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 self.settings = server_data
def do_server_setup(self, server_data_obj): def do_server_setup(self, server_data_obj):
serverId = server_data_obj["server_id"] server_id = server_data_obj["server_id"]
serverName = server_data_obj["server_name"] server_name = server_data_obj["server_name"]
autoStart = server_data_obj["auto_start"] auto_start = server_data_obj["auto_start"]
logger.info( logger.info(
f"Creating Server object: {serverId} | " f"Creating Server object: {server_id} | "
f"Server Name: {serverName} | " f"Server Name: {server_name} | "
f"Auto Start: {autoStart}" f"Auto Start: {auto_start}"
) )
self.server_id = serverId self.server_id = server_id
self.name = serverName self.name = server_name
self.settings = server_data_obj self.settings = server_data_obj
self.record_server_stats() self.record_server_stats()
@ -163,7 +163,7 @@ class Server:
Console.info(f"Starting server ID: {self.server_id} - {self.name}") Console.info(f"Starting server ID: {self.server_id} - {self.name}")
logger.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. # 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) self.run_threaded_server(None)
# remove the scheduled job since it's ran # remove the scheduled job since it's ran
@ -228,9 +228,9 @@ class Server:
if not user_id: if not user_id:
user_lang = self.helper.get_setting("language") user_lang = self.helper.get_setting("language")
else: 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: if user_id:
self.helper.websocket_helper.broadcast_user( self.helper.websocket_helper.broadcast_user(
user_id, user_id,
@ -310,7 +310,7 @@ class Server:
f = open( f = open(
os.path.join( os.path.join(
self.server_path, 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", "r",
encoding="utf-8", encoding="utf-8",
@ -332,7 +332,7 @@ class Server:
if ( if (
not Helpers.is_os_windows() 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" == "minecraft-bedrock"
): ):
logger.info( logger.info(
@ -413,7 +413,7 @@ class Server:
).start() ).start()
self.is_crashed = False 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")) 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}") logger.info(f"Server {self.name} running with PID {self.process.pid}")
Console.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 self.is_crashed = False
helper_servers.server_crash_reset(self.server_id) HelperServers.server_crash_reset(self.server_id)
self.record_server_stats() self.record_server_stats()
check_internet_thread = threading.Thread( check_internet_thread = threading.Thread(
target=self.check_internet_thread, target=self.check_internet_thread,
@ -434,9 +434,9 @@ class Server:
) )
check_internet_thread.start() check_internet_thread.start()
# Checks if this is the servers first run. # Checks if this is the servers first run.
if helper_servers.get_first_run(self.server_id): if HelperServers.get_first_run(self.server_id):
helper_servers.set_first_run(self.server_id) HelperServers.set_first_run(self.server_id)
loc_server_port = helper_servers.get_server_stats_by_id(self.server_id)[ loc_server_port = HelperServers.get_server_stats_by_id(self.server_id)[
"server_port" "server_port"
] ]
# Sends port reminder message. # Sends port reminder message.
@ -449,14 +449,14 @@ class Server:
).format(self.name, loc_server_port) ).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: for user in server_users:
if user != user_id: if user != user_id:
self.helper.websocket_helper.broadcast_user( self.helper.websocket_helper.broadcast_user(
user, "send_start_reload", {} user, "send_start_reload", {}
) )
else: 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: for user in server_users:
self.helper.websocket_helper.broadcast_user( self.helper.websocket_helper.broadcast_user(
user, "send_start_reload", {} user, "send_start_reload", {}
@ -554,17 +554,17 @@ class Server:
logger.info(f"Can't stop server {self.name} if it's not running") 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") Console.info(f"Can't stop server {self.name} if it's not running")
return return
x = 0 i = 0
# caching the name and pid number # caching the name and pid number
server_name = self.name server_name = self.name
server_pid = self.process.pid server_pid = self.process.pid
while running: while running:
x = x + 1 i += 1
logstr = ( logstr = (
f"Server {server_name} is still running " 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)" f"seconds until force close)"
) )
logger.info(logstr) logger.info(logstr)
@ -573,7 +573,7 @@ class Server:
time.sleep(2) time.sleep(2)
# if we haven't closed in 60 seconds, let's just slam down on the PID # if we haven't closed in 60 seconds, let's just slam down on the PID
if x >= 30: if i >= 30:
logger.info( logger.info(
f"Server {server_name} is still running - Forcing the process down" f"Server {server_name} is still running - Forcing the process down"
) )
@ -587,7 +587,7 @@ class Server:
# massive resetting of variables # massive resetting of variables
self.cleanup_server_object() 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 # remove the stats polling job since server is stopped
self.server_scheduler.remove_job("stats_" + str(self.server_id)) 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)) self.server_scheduler.remove_job("c_" + str(self.server_id))
return 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 we haven't tried to restart more 3 or more times
if self.restart_count <= 3: if self.restart_count <= 3:
@ -742,7 +742,7 @@ class Server:
self.restart_count = 0 self.restart_count = 0
self.is_crashed = True self.is_crashed = True
helper_servers.sever_crashed(self.server_id) HelperServers.sever_crashed(self.server_id)
# cancel the watcher task # cancel the watcher task
self.server_scheduler.remove_job("c_" + str(self.server_id)) self.server_scheduler.remove_job("c_" + str(self.server_id))
@ -806,17 +806,17 @@ class Server:
{"percent": 0, "total_files": 0}, {"percent": 0, "total_files": 0},
) )
logger.info(f"Starting server {self.name} (ID {self.server_id}) backup") 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: for user in server_users:
self.helper.websocket_helper.broadcast_user( self.helper.websocket_helper.broadcast_user(
user, user,
"notification", "notification",
self.helper.translation.translate( 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), ).format(self.name),
) )
time.sleep(3) 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"]) self.helper.ensure_dir_exists(self.settings["backup_path"])
try: try:
backup_filename = ( backup_filename = (
@ -829,17 +829,17 @@ class Server:
f"at '{backup_filename}'" f"at '{backup_filename}'"
) )
tempDir = tempfile.mkdtemp() temp_dir = tempfile.mkdtemp()
self.server_scheduler.add_job( self.server_scheduler.add_job(
self.backup_status, self.backup_status,
"interval", "interval",
seconds=1, seconds=1,
id="backup_" + str(self.server_id), id="backup_" + str(self.server_id),
args=[tempDir + "/", backup_filename + ".zip"], args=[temp_dir + "/", backup_filename + ".zip"],
) )
# pylint: disable=unexpected-keyword-arg # pylint: disable=unexpected-keyword-arg
FileHelpers.copy_dir(self.server_path, tempDir, dirs_exist_ok=True) FileHelpers.copy_dir(self.server_path, temp_dir, dirs_exist_ok=True)
excluded_dirs = helpers_management.get_excluded_backup_dirs(self.server_id) excluded_dirs = HelpersManagement.get_excluded_backup_dirs(self.server_id)
server_dir = Helpers.get_os_understandable_path(self.settings["path"]) server_dir = Helpers.get_os_understandable_path(self.settings["path"])
for my_dir in excluded_dirs: for my_dir in excluded_dirs:
@ -848,7 +848,7 @@ class Server:
# only deleting excluded dirs from the temp path # only deleting excluded dirs from the temp path
# and not the server path # and not the server path
excluded_dir = Helpers.get_os_understandable_path(my_dir).replace( 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 # Next, check to see if it is a directory
if os.path.isdir(excluded_dir): if os.path.isdir(excluded_dir):
@ -863,14 +863,14 @@ class Server:
"Found compress backup to be true. Calling compressed archive" "Found compress backup to be true. Calling compressed archive"
) )
FileHelpers.make_compressed_archive( FileHelpers.make_compressed_archive(
Helpers.get_os_understandable_path(backup_filename), tempDir Helpers.get_os_understandable_path(backup_filename), temp_dir
) )
else: else:
logger.debug( logger.debug(
"Found compress backup to be false. Calling NON-compressed archive" "Found compress backup to be false. Calling NON-compressed archive"
) )
FileHelpers.make_archive( FileHelpers.make_archive(
Helpers.get_os_understandable_path(backup_filename), tempDir Helpers.get_os_understandable_path(backup_filename), temp_dir
) )
while ( while (
@ -884,7 +884,7 @@ class Server:
os.remove(Helpers.get_os_understandable_path(oldfile_path)) os.remove(Helpers.get_os_understandable_path(oldfile_path))
self.is_backingup = False self.is_backingup = False
FileHelpers.del_dirs(tempDir) FileHelpers.del_dirs(temp_dir)
logger.info(f"Backup of server: {self.name} completed") logger.info(f"Backup of server: {self.name} completed")
self.server_scheduler.remove_job("backup_" + str(self.server_id)) self.server_scheduler.remove_job("backup_" + str(self.server_id))
results = {"percent": 100, "total_files": 0, "current_file": 0} results = {"percent": 100, "total_files": 0, "current_file": 0}
@ -895,7 +895,7 @@ class Server:
"backup_status", "backup_status",
results, 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: for user in server_users:
self.helper.websocket_helper.broadcast_user( self.helper.websocket_helper.broadcast_user(
user, user,
@ -903,7 +903,7 @@ class Server:
self.helper.translation.translate( self.helper.translation.translate(
"notify", "notify",
"backupComplete", "backupComplete",
helper_users.get_user_lang_by_id(user), HelperUsers.get_user_lang_by_id(user),
).format(self.name), ).format(self.name),
) )
time.sleep(3) time.sleep(3)
@ -972,7 +972,7 @@ class Server:
return [] return []
def jar_update(self): def jar_update(self):
helper_servers.set_update(self.server_id, True) HelperServers.set_update(self.server_id, True)
update_thread = threading.Thread( update_thread = threading.Thread(
target=self.a_jar_update, daemon=True, name=f"exe_update_{self.name}" target=self.a_jar_update, daemon=True, name=f"exe_update_{self.name}"
) )
@ -980,24 +980,24 @@ class Server:
def check_update(self): 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 return True
else: else:
return False return False
def a_jar_update(self): def a_jar_update(self):
wasStarted = "-1" was_started = "-1"
self.backup_server() self.backup_server()
# checks if server is running. Calls shutdown if it is running. # checks if server is running. Calls shutdown if it is running.
if self.check_running(): if self.check_running():
wasStarted = True was_started = True
logger.info( logger.info(
f"Server with PID {self.process.pid} is running. " f"Server with PID {self.process.pid} is running. "
f"Sending shutdown command" f"Sending shutdown command"
) )
self.stop_threaded_server() self.stop_threaded_server()
else: else:
wasStarted = False was_started = False
if len(self.helper.websocket_helper.clients) > 0: if len(self.helper.websocket_helper.clients) > 0:
# There are clients # There are clients
self.check_update() self.check_update()
@ -1010,7 +1010,7 @@ class Server:
{ {
"isUpdating": self.check_update(), "isUpdating": self.check_update(),
"server_id": self.server_id, "server_id": self.server_id,
"wasRunning": wasStarted, "wasRunning": was_started,
"string": message, "string": message,
}, },
) )
@ -1053,15 +1053,15 @@ class Server:
self.settings["executable_update_url"], current_executable 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: if downloaded and not self.is_backingup:
logger.info("Executable updated successfully. Starting Server") 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: if len(self.helper.websocket_helper.clients) > 0:
# There are clients # There are clients
self.check_update() self.check_update()
server_users = Permissions_Servers.get_server_user_list( server_users = PermissionsServers.get_server_user_list(
self.server_id self.server_id
) )
for user in server_users: for user in server_users:
@ -1077,13 +1077,13 @@ class Server:
{ {
"isUpdating": self.check_update(), "isUpdating": self.check_update(),
"server_id": self.server_id, "server_id": self.server_id,
"wasRunning": wasStarted, "wasRunning": was_started,
}, },
) )
self.helper.websocket_helper.broadcast_page( self.helper.websocket_helper.broadcast_page(
"/panel/dashboard", "send_start_reload", {} "/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: for user in server_users:
self.helper.websocket_helper.broadcast_user( self.helper.websocket_helper.broadcast_user(
user, user,
@ -1098,11 +1098,11 @@ class Server:
"Executable update finished for " + self.name, "Executable update finished for " + self.name,
self.settings["server_ip"], self.settings["server_ip"],
) )
if wasStarted: if was_started:
self.start_server() self.start_server()
elif not downloaded and not self.is_backingup: elif not downloaded and not self.is_backingup:
time.sleep(5) 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: for user in server_users:
self.helper.websocket_helper.broadcast_user( self.helper.websocket_helper.broadcast_user(
user, user,
@ -1194,7 +1194,7 @@ class Server:
logger.info("Getting Stats for Server " + self.name + " ...") logger.info("Getting Stats for Server " + self.name + " ...")
server_id = self.server_id 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}") 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}") server_name = server.get("server_name", f"ID#{server_id}")
logger.debug(f"Pinging server '{server}' on {internal_ip}:{server_port}") 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)) int_mc_ping = ping_bedrock(internal_ip, int(server_port))
else: else:
int_mc_ping = ping(internal_ip, int(server_port)) int_mc_ping = ping(internal_ip, int(server_port))
@ -1225,10 +1225,10 @@ class Server:
if int_mc_ping: if int_mc_ping:
int_data = True int_data = True
if ( if (
helper_servers.get_server_type_by_id(server["server_id"]) HelperServers.get_server_type_by_id(server["server_id"])
== "minecraft-bedrock" == "minecraft-bedrock"
): ):
ping_data = Stats.parse_server_RakNet_ping(int_mc_ping) ping_data = Stats.parse_server_raknet_ping(int_mc_ping)
else: else:
ping_data = Stats.parse_server_ping(int_mc_ping) ping_data = Stats.parse_server_ping(int_mc_ping)
# Makes sure we only show stats when a server is online # Makes sure we only show stats when a server is online
@ -1274,7 +1274,7 @@ class Server:
def get_server_players(self): 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}") logger.info(f"Getting players for server {server}")
@ -1287,7 +1287,7 @@ class Server:
server_port = server["server_port"] server_port = server["server_port"]
logger.debug(f"Pinging {internal_ip} on port {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)) int_mc_ping = ping(internal_ip, int(server_port))
ping_data = {} ping_data = {}
@ -1301,7 +1301,7 @@ class Server:
def get_raw_server_stats(self, server_id): def get_raw_server_stats(self, server_id):
try: try:
server = helper_servers.get_server_obj(server_id) server = HelperServers.get_server_obj(server_id)
except: except:
return { return {
"id": server_id, "id": server_id,
@ -1323,10 +1323,10 @@ class Server:
} }
server_stats = {} server_stats = {}
server = helper_servers.get_server_obj(server_id) server = HelperServers.get_server_obj(server_id)
if not server: if not server:
return {} 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}") logger.debug(f"Getting stats for server: {server_id}")
@ -1347,7 +1347,7 @@ class Server:
server_port = server_dt["server_port"] server_port = server_dt["server_port"]
logger.debug(f"Pinging server '{self.name}' on {internal_ip}:{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)) int_mc_ping = ping_bedrock(internal_ip, int(server_port))
else: else:
int_mc_ping = ping(internal_ip, int(server_port)) int_mc_ping = ping(internal_ip, int(server_port))
@ -1358,7 +1358,7 @@ class Server:
# otherwise people have gotten confused. # otherwise people have gotten confused.
if self.check_running(): if self.check_running():
# if we got a good ping return, let's parse it # 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: if int_mc_ping:
int_data = True int_data = True
ping_data = Stats.parse_server_ping(int_mc_ping) ping_data = Stats.parse_server_ping(int_mc_ping)
@ -1385,7 +1385,7 @@ class Server:
else: else:
if int_mc_ping: if int_mc_ping:
int_data = True int_data = True
ping_data = Stats.parse_server_RakNet_ping(int_mc_ping) ping_data = Stats.parse_server_raknet_ping(int_mc_ping)
try: try:
server_icon = base64.encodebytes(ping_data["icon"]) server_icon = base64.encodebytes(ping_data["icon"])
except Exception as ex: except Exception as ex:
@ -1453,23 +1453,23 @@ class Server:
def record_server_stats(self): def record_server_stats(self):
server = self.get_servers_stats() server = self.get_servers_stats()
Server_Stats.insert( ServerStats.insert(
{ {
Server_Stats.server_id: server.get("id", 0), ServerStats.server_id: server.get("id", 0),
Server_Stats.started: server.get("started", ""), ServerStats.started: server.get("started", ""),
Server_Stats.running: server.get("running", False), ServerStats.running: server.get("running", False),
Server_Stats.cpu: server.get("cpu", 0), ServerStats.cpu: server.get("cpu", 0),
Server_Stats.mem: server.get("mem", 0), ServerStats.mem: server.get("mem", 0),
Server_Stats.mem_percent: server.get("mem_percent", 0), ServerStats.mem_percent: server.get("mem_percent", 0),
Server_Stats.world_name: server.get("world_name", ""), ServerStats.world_name: server.get("world_name", ""),
Server_Stats.world_size: server.get("world_size", ""), ServerStats.world_size: server.get("world_size", ""),
Server_Stats.server_port: server.get("server_port", ""), ServerStats.server_port: server.get("server_port", ""),
Server_Stats.int_ping_results: server.get("int_ping_results", False), ServerStats.int_ping_results: server.get("int_ping_results", False),
Server_Stats.online: server.get("online", False), ServerStats.online: server.get("online", False),
Server_Stats.max: server.get("max", False), ServerStats.max: server.get("max", False),
Server_Stats.players: server.get("players", False), ServerStats.players: server.get("players", False),
Server_Stats.desc: server.get("desc", False), ServerStats.desc: server.get("desc", False),
Server_Stats.version: server.get("version", False), ServerStats.version: server.get("version", False),
} }
).execute() ).execute()
@ -1478,4 +1478,4 @@ class Server:
now = datetime.datetime.now() now = datetime.datetime.now()
last_week = now.day - max_age last_week = now.day - max_age
Server_Stats.delete().where(Server_Stats.created < last_week).execute() ServerStats.delete().where(ServerStats.created < last_week).execute()

View File

@ -9,8 +9,8 @@ from apscheduler.events import EVENT_JOB_EXECUTED
from apscheduler.schedulers.background import BackgroundScheduler from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger from apscheduler.triggers.cron import CronTrigger
from app.classes.models.management import helpers_management from app.classes.models.management import HelpersManagement
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.console import Console
from app.classes.web.tornado_handler import Webserver from app.classes.web.tornado_handler import Webserver
@ -70,7 +70,7 @@ class TasksManager:
return self.main_thread_exiting return self.main_thread_exiting
def reload_schedule_from_db(self): 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: ") logger.info("Reload from DB called. Current enabled schedules: ")
for item in jobs: for item in jobs:
logger.info(f"JOB: {item}") logger.info(f"JOB: {item}")
@ -78,19 +78,19 @@ class TasksManager:
def command_watcher(self): def command_watcher(self):
while True: while True:
# select any commands waiting to be processed # select any commands waiting to be processed
commands = helpers_management.get_unactioned_commands() commands = HelpersManagement.get_unactioned_commands()
for c in commands: for cmd in commands:
try: try:
svr = self.controller.get_server_obj(c.server_id) svr = self.controller.get_server_obj(cmd.server_id)
except: except:
logger.error( logger.error(
"Server value requested does note exist! " "Server value requested does note exist! "
"Purging item from waiting commands." "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 user_id = cmd.user_id
command = c.command command = cmd.command
if command == "start_server": if command == "start_server":
svr.run_threaded_server(user_id) svr.run_threaded_server(user_id)
@ -108,7 +108,7 @@ class TasksManager:
svr.jar_update() svr.jar_update()
else: else:
svr.send_command(command) svr.send_command(command)
helpers_management.mark_command_complete(c.command_id) HelpersManagement.mark_command_complete(cmd.command_id)
time.sleep(1) time.sleep(1)
@ -153,7 +153,7 @@ class TasksManager:
self.realtime_thread.start() self.realtime_thread.start()
def scheduler_thread(self): 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_listener(self.schedule_watcher, mask=EVENT_JOB_EXECUTED)
# self.scheduler.add_job( # self.scheduler.add_job(
# self.scheduler.print_jobs, "interval", seconds=10, id="-1" # self.scheduler.print_jobs, "interval", seconds=10, id="-1"
@ -165,7 +165,7 @@ class TasksManager:
if schedule.cron_string != "": if schedule.cron_string != "":
try: try:
self.scheduler.add_job( self.scheduler.add_job(
helpers_management.add_command, HelpersManagement.add_command,
CronTrigger.from_crontab( CronTrigger.from_crontab(
schedule.cron_string, timezone=str(self.tz) schedule.cron_string, timezone=str(self.tz)
), ),
@ -189,7 +189,7 @@ class TasksManager:
else: else:
if schedule.interval_type == "hours": if schedule.interval_type == "hours":
self.scheduler.add_job( self.scheduler.add_job(
helpers_management.add_command, HelpersManagement.add_command,
"cron", "cron",
minute=0, minute=0,
hour="*/" + str(schedule.interval), hour="*/" + str(schedule.interval),
@ -203,7 +203,7 @@ class TasksManager:
) )
elif schedule.interval_type == "minutes": elif schedule.interval_type == "minutes":
self.scheduler.add_job( self.scheduler.add_job(
helpers_management.add_command, HelpersManagement.add_command,
"cron", "cron",
minute="*/" + str(schedule.interval), minute="*/" + str(schedule.interval),
id=str(schedule.schedule_id), id=str(schedule.schedule_id),
@ -217,7 +217,7 @@ class TasksManager:
elif schedule.interval_type == "days": elif schedule.interval_type == "days":
curr_time = schedule.start_time.split(":") curr_time = schedule.start_time.split(":")
self.scheduler.add_job( self.scheduler.add_job(
helpers_management.add_command, HelpersManagement.add_command,
"cron", "cron",
day="*/" + str(schedule.interval), day="*/" + str(schedule.interval),
hour=curr_time[0], hour=curr_time[0],
@ -237,7 +237,7 @@ class TasksManager:
logger.info(f"JOB: {item}") logger.info(f"JOB: {item}")
def schedule_job(self, job_data): 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["server_id"],
job_data["action"], job_data["action"],
job_data["interval"], job_data["interval"],
@ -254,13 +254,13 @@ class TasksManager:
# Checks to make sure some doofus didn't actually make the newly # Checks to make sure some doofus didn't actually make the newly
# created task a child of itself. # created task a child of itself.
if str(job_data["parent"]) == str(sch_id): 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. # 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["enabled"] and job_data["interval_type"] != "reaction":
if job_data["cron_string"] != "": if job_data["cron_string"] != "":
try: try:
self.scheduler.add_job( self.scheduler.add_job(
helpers_management.add_command, HelpersManagement.add_command,
CronTrigger.from_crontab( CronTrigger.from_crontab(
job_data["cron_string"], timezone=str(self.tz) job_data["cron_string"], timezone=str(self.tz)
), ),
@ -282,7 +282,7 @@ class TasksManager:
else: else:
if job_data["interval_type"] == "hours": if job_data["interval_type"] == "hours":
self.scheduler.add_job( self.scheduler.add_job(
helpers_management.add_command, HelpersManagement.add_command,
"cron", "cron",
minute=0, minute=0,
hour="*/" + str(job_data["interval"]), hour="*/" + str(job_data["interval"]),
@ -296,7 +296,7 @@ class TasksManager:
) )
elif job_data["interval_type"] == "minutes": elif job_data["interval_type"] == "minutes":
self.scheduler.add_job( self.scheduler.add_job(
helpers_management.add_command, HelpersManagement.add_command,
"cron", "cron",
minute="*/" + str(job_data["interval"]), minute="*/" + str(job_data["interval"]),
id=str(sch_id), id=str(sch_id),
@ -310,7 +310,7 @@ class TasksManager:
elif job_data["interval_type"] == "days": elif job_data["interval_type"] == "days":
curr_time = job_data["start_time"].split(":") curr_time = job_data["start_time"].split(":")
self.scheduler.add_job( self.scheduler.add_job(
helpers_management.add_command, HelpersManagement.add_command,
"cron", "cron",
day="*/" + str(job_data["interval"]), day="*/" + str(job_data["interval"]),
hour=curr_time[0], hour=curr_time[0],
@ -329,14 +329,14 @@ class TasksManager:
logger.info(f"JOB: {item}") logger.info(f"JOB: {item}")
def remove_all_server_tasks(self, server_id): 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: for schedule in schedules:
if schedule.interval != "reaction": if schedule.interval != "reaction":
self.remove_job(schedule.schedule_id) self.remove_job(schedule.schedule_id)
def remove_job(self, sch_id): def remove_job(self, sch_id):
job = helpers_management.get_scheduled_task_model(sch_id) job = HelpersManagement.get_scheduled_task_model(sch_id)
for schedule in helpers_management.get_child_schedules(sch_id): for schedule in HelpersManagement.get_child_schedules(sch_id):
self.controller.management_helper.update_scheduled_task( self.controller.management_helper.update_scheduled_task(
schedule.schedule_id, {"parent": None} schedule.schedule_id, {"parent": None}
) )
@ -352,11 +352,11 @@ class TasksManager:
) )
def update_job(self, sch_id, job_data): 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 # Checks to make sure some doofus didn't actually make the newly
# created task a child of itself. # created task a child of itself.
if str(job_data["parent"]) == str(sch_id): 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: try:
if job_data["interval"] != "reaction": if job_data["interval"] != "reaction":
self.scheduler.remove_job(str(sch_id)) self.scheduler.remove_job(str(sch_id))
@ -371,7 +371,7 @@ class TasksManager:
if job_data["cron_string"] != "": if job_data["cron_string"] != "":
try: try:
self.scheduler.add_job( self.scheduler.add_job(
helpers_management.add_command, HelpersManagement.add_command,
CronTrigger.from_crontab( CronTrigger.from_crontab(
job_data["cron_string"], timezone=str(self.tz) job_data["cron_string"], timezone=str(self.tz)
), ),
@ -390,7 +390,7 @@ class TasksManager:
else: else:
if job_data["interval_type"] == "hours": if job_data["interval_type"] == "hours":
self.scheduler.add_job( self.scheduler.add_job(
helpers_management.add_command, HelpersManagement.add_command,
"cron", "cron",
minute=0, minute=0,
hour="*/" + str(job_data["interval"]), hour="*/" + str(job_data["interval"]),
@ -404,7 +404,7 @@ class TasksManager:
) )
elif job_data["interval_type"] == "minutes": elif job_data["interval_type"] == "minutes":
self.scheduler.add_job( self.scheduler.add_job(
helpers_management.add_command, HelpersManagement.add_command,
"cron", "cron",
minute="*/" + str(job_data["interval"]), minute="*/" + str(job_data["interval"]),
id=str(sch_id), id=str(sch_id),
@ -418,7 +418,7 @@ class TasksManager:
elif job_data["interval_type"] == "days": elif job_data["interval_type"] == "days":
curr_time = job_data["start_time"].split(":") curr_time = job_data["start_time"].split(":")
self.scheduler.add_job( self.scheduler.add_job(
helpers_management.add_command, HelpersManagement.add_command,
"cron", "cron",
day="*/" + str(job_data["interval"]), day="*/" + str(job_data["interval"]),
hour=curr_time[0], hour=curr_time[0],
@ -449,7 +449,7 @@ class TasksManager:
) )
self.controller.management.add_to_audit_log_raw( self.controller.management.add_to_audit_log_raw(
"system", "system",
helper_users.get_user_id_by_name("system"), HelperUsers.get_user_id_by_name("system"),
task.server_id, task.server_id,
f"Task with id {task.schedule_id} completed successfully", f"Task with id {task.schedule_id} completed successfully",
"127.0.0.1", "127.0.0.1",
@ -461,7 +461,7 @@ class TasksManager:
# check for any child tasks for this. It's kind of backward, # check for any child tasks for this. It's kind of backward,
# but this makes DB management a lot easier. One to one # but this makes DB management a lot easier. One to one
# instead of one to many. # 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 task.schedule_id, task.server_id
): ):
# event job ID's are strings so we need to look at # event job ID's are strings so we need to look at
@ -472,7 +472,7 @@ class TasksManager:
seconds=schedule.delay seconds=schedule.delay
) )
self.scheduler.add_job( self.scheduler.add_job(
helpers_management.add_command, HelpersManagement.add_command,
"date", "date",
run_date=delaytime, run_date=delaytime,
id=str(schedule.schedule_id), id=str(schedule.schedule_id),
@ -526,22 +526,22 @@ class TasksManager:
loop = asyncio.new_event_loop() loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop) asyncio.set_event_loop(loop)
host_stats = helpers_management.get_latest_hosts_stats() host_stats = HelpersManagement.get_latest_hosts_stats()
while True: while True:
if host_stats.get( if host_stats.get(
"cpu_usage" "cpu_usage"
) != helpers_management.get_latest_hosts_stats().get( ) != HelpersManagement.get_latest_hosts_stats().get(
"cpu_usage" "cpu_usage"
) or host_stats.get( ) or host_stats.get(
"mem_percent" "mem_percent"
) != helpers_management.get_latest_hosts_stats().get( ) != HelpersManagement.get_latest_hosts_stats().get(
"mem_percent" "mem_percent"
): ):
# Stats are different # 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: if len(self.helper.websocket_helper.clients) > 0:
# There are clients # There are clients
self.helper.websocket_helper.broadcast_page( self.helper.websocket_helper.broadcast_page(

View File

@ -7,7 +7,7 @@ import bleach
import tornado.web import tornado.web
import tornado.escape 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.console import Console
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
from app.classes.shared.server import ServerOutBuf from app.classes.shared.server import ServerOutBuf
@ -68,11 +68,13 @@ class AjaxHandler(BaseHandler):
else: else:
data = ServerOutBuf.lines.get(server_id, []) data = ServerOutBuf.lines.get(server_id, [])
for d in data: for line in data:
try: try:
d = re.sub("(\033\\[(0;)?[0-9]*[A-z]?(;[0-9])?m?)|(> )", "", d) line = re.sub(
d = re.sub("[A-z]{2}\b\b", "", d) "(\033\\[(0;)?[0-9]*[A-z]?(;[0-9])?m?)|(> )", "", line
line = self.helper.log_colors(html.escape(d)) )
line = re.sub("[A-z]{2}\b\b", "", line)
line = self.helper.log_colors(html.escape(line))
self.write(f"{line}<br />") self.write(f"{line}<br />")
# self.write(d.encode("utf-8")) # self.write(d.encode("utf-8"))
@ -265,14 +267,14 @@ class AjaxHandler(BaseHandler):
server_id = self.get_argument("id", None) server_id = self.get_argument("id", None)
permissions = { permissions = {
"Commands": Enum_Permissions_Server.Commands, "Commands": EnumPermissionsServer.COMMANDS,
"Terminal": Enum_Permissions_Server.Terminal, "Terminal": EnumPermissionsServer.TERMINAL,
"Logs": Enum_Permissions_Server.Logs, "Logs": EnumPermissionsServer.LOGS,
"Schedule": Enum_Permissions_Server.Schedule, "Schedule": EnumPermissionsServer.SCHEDULE,
"Backup": Enum_Permissions_Server.Backup, "Backup": EnumPermissionsServer.BACKUP,
"Files": Enum_Permissions_Server.Files, "Files": EnumPermissionsServer.FILES,
"Config": Enum_Permissions_Server.Config, "Config": EnumPermissionsServer.CONFIG,
"Players": Enum_Permissions_Server.Players, "Players": EnumPermissionsServer.PLAYERS,
} }
user_perms = self.controller.server_perms.get_user_id_permissions_list( user_perms = self.controller.server_perms.get_user_id_permissions_list(
exec_user["user_id"], server_id exec_user["user_id"], server_id
@ -384,10 +386,10 @@ class AjaxHandler(BaseHandler):
if server_data["type"] == "minecraft-java": if server_data["type"] == "minecraft-java":
backup_path = svr_obj.backup_path backup_path = svr_obj.backup_path
if Helpers.validate_traversal(backup_path, zip_name): 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( new_server = self.controller.import_zip_server(
svr_obj.server_name, svr_obj.server_name,
tempDir, temp_dir,
server_data["executable"], server_data["executable"],
"1", "1",
"2", "2",
@ -404,10 +406,10 @@ class AjaxHandler(BaseHandler):
else: else:
backup_path = svr_obj.backup_path backup_path = svr_obj.backup_path
if Helpers.validate_traversal(backup_path, zip_name): 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( new_server = self.controller.import_bedrock_zip_server(
svr_obj.server_name, svr_obj.server_name,
tempDir, temp_dir,
server_data["executable"], server_data["executable"],
server_data["server_port"], server_data["server_port"],
) )
@ -422,7 +424,7 @@ class AjaxHandler(BaseHandler):
elif page == "unzip_server": elif page == "unzip_server":
path = self.get_argument("path", None) path = self.get_argument("path", None)
if Helpers.check_file_exists(path): if Helpers.check_file_exists(path):
self.helper.unzipServer(path, exec_user["user_id"]) self.helper.unzip_server(path, exec_user["user_id"])
else: else:
user_id = exec_user["user_id"] user_id = exec_user["user_id"]
if user_id: if user_id:
@ -454,14 +456,14 @@ class AjaxHandler(BaseHandler):
server_id = self.get_argument("id", None) server_id = self.get_argument("id", None)
permissions = { permissions = {
"Commands": Enum_Permissions_Server.Commands, "Commands": EnumPermissionsServer.COMMANDS,
"Terminal": Enum_Permissions_Server.Terminal, "Terminal": EnumPermissionsServer.TERMINAL,
"Logs": Enum_Permissions_Server.Logs, "Logs": EnumPermissionsServer.LOGS,
"Schedule": Enum_Permissions_Server.Schedule, "Schedule": EnumPermissionsServer.SCHEDULE,
"Backup": Enum_Permissions_Server.Backup, "Backup": EnumPermissionsServer.BACKUP,
"Files": Enum_Permissions_Server.Files, "Files": EnumPermissionsServer.FILES,
"Config": Enum_Permissions_Server.Config, "Config": EnumPermissionsServer.CONFIG,
"Players": Enum_Permissions_Server.Players, "Players": EnumPermissionsServer.PLAYERS,
} }
user_perms = self.controller.server_perms.get_user_id_permissions_list( user_perms = self.controller.server_perms.get_user_id_permissions_list(
exec_user["user_id"], server_id exec_user["user_id"], server_id

View File

@ -2,8 +2,8 @@ from datetime import datetime
import logging import logging
import re import re
from app.classes.controllers.crafty_perms_controller import Enum_Permissions_Crafty from app.classes.controllers.crafty_perms_controller import EnumPermissionsCrafty
from app.classes.controllers.server_perms_controller import Enum_Permissions_Server from app.classes.controllers.server_perms_controller import EnumPermissionsServer
from app.classes.web.base_handler import BaseHandler from app.classes.web.base_handler import BaseHandler
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -42,17 +42,17 @@ class ApiHandler(BaseHandler):
def authenticate_user(self) -> bool: def authenticate_user(self) -> bool:
self.permissions = { self.permissions = {
"Commands": Enum_Permissions_Server.Commands, "Commands": EnumPermissionsServer.COMMANDS,
"Terminal": Enum_Permissions_Server.Terminal, "Terminal": EnumPermissionsServer.TERMINAL,
"Logs": Enum_Permissions_Server.Logs, "Logs": EnumPermissionsServer.LOGS,
"Schedule": Enum_Permissions_Server.Schedule, "Schedule": EnumPermissionsServer.SCHEDULE,
"Backup": Enum_Permissions_Server.Backup, "Backup": EnumPermissionsServer.BACKUP,
"Files": Enum_Permissions_Server.Files, "Files": EnumPermissionsServer.FILES,
"Config": Enum_Permissions_Server.Config, "Config": EnumPermissionsServer.CONFIG,
"Players": Enum_Permissions_Server.Players, "Players": EnumPermissionsServer.PLAYERS,
"Server_Creation": Enum_Permissions_Crafty.Server_Creation, "Server_Creation": EnumPermissionsCrafty.SERVER_CREATION,
"User_Config": Enum_Permissions_Crafty.User_Config, "User_Config": EnumPermissionsCrafty.USER_CONFIG,
"Roles_Config": Enum_Permissions_Crafty.Roles_Config, "Roles_Config": EnumPermissionsCrafty.ROLES_CONFIG,
} }
try: try:
logger.debug("Searching for specified token") logger.debug("Searching for specified token")

View File

@ -8,8 +8,7 @@ logger = logging.getLogger(__name__)
class DefaultHandler(BaseHandler): class DefaultHandler(BaseHandler):
# Override prepare() instead of get() to cover all possible HTTP methods. # Override prepare() instead of get() to cover all possible HTTP methods.
# pylint: disable=arguments-differ def prepare(self, page=None): # pylint: disable=arguments-differ
def prepare(self, page=None):
if page is not None: if page is not None:
self.set_status(404) self.set_status(404)
self.render( self.render(

View File

@ -4,7 +4,7 @@ import bleach
import tornado.web import tornado.web
import tornado.escape 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.console import Console
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
from app.classes.shared.file_helpers import FileHelpers from app.classes.shared.file_helpers import FileHelpers
@ -31,14 +31,14 @@ class FileHandler(BaseHandler):
server_id = self.get_argument("id", None) server_id = self.get_argument("id", None)
permissions = { permissions = {
"Commands": Enum_Permissions_Server.Commands, "Commands": EnumPermissionsServer.COMMANDS,
"Terminal": Enum_Permissions_Server.Terminal, "Terminal": EnumPermissionsServer.TERMINAL,
"Logs": Enum_Permissions_Server.Logs, "Logs": EnumPermissionsServer.LOGS,
"Schedule": Enum_Permissions_Server.Schedule, "Schedule": EnumPermissionsServer.SCHEDULE,
"Backup": Enum_Permissions_Server.Backup, "Backup": EnumPermissionsServer.BACKUP,
"Files": Enum_Permissions_Server.Files, "Files": EnumPermissionsServer.FILES,
"Config": Enum_Permissions_Server.Config, "Config": EnumPermissionsServer.CONFIG,
"Players": Enum_Permissions_Server.Players, "Players": EnumPermissionsServer.PLAYERS,
} }
user_perms = self.controller.server_perms.get_user_id_permissions_list( user_perms = self.controller.server_perms.get_user_id_permissions_list(
exec_user["user_id"], server_id exec_user["user_id"], server_id
@ -138,14 +138,14 @@ class FileHandler(BaseHandler):
server_id = self.get_argument("id", None) server_id = self.get_argument("id", None)
permissions = { permissions = {
"Commands": Enum_Permissions_Server.Commands, "Commands": EnumPermissionsServer.COMMANDS,
"Terminal": Enum_Permissions_Server.Terminal, "Terminal": EnumPermissionsServer.TERMINAL,
"Logs": Enum_Permissions_Server.Logs, "Logs": EnumPermissionsServer.LOGS,
"Schedule": Enum_Permissions_Server.Schedule, "Schedule": EnumPermissionsServer.SCHEDULE,
"Backup": Enum_Permissions_Server.Backup, "Backup": EnumPermissionsServer.BACKUP,
"Files": Enum_Permissions_Server.Files, "Files": EnumPermissionsServer.FILES,
"Config": Enum_Permissions_Server.Config, "Config": EnumPermissionsServer.CONFIG,
"Players": Enum_Permissions_Server.Players, "Players": EnumPermissionsServer.PLAYERS,
} }
user_perms = self.controller.server_perms.get_user_id_permissions_list( user_perms = self.controller.server_perms.get_user_id_permissions_list(
exec_user["user_id"], server_id exec_user["user_id"], server_id
@ -223,7 +223,7 @@ class FileHandler(BaseHandler):
self.redirect("/panel/error?error=Unauthorized access to Files") self.redirect("/panel/error?error=Unauthorized access to Files")
return return
path = Helpers.get_os_understandable_path(self.get_argument("path", None)) 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") self.redirect(f"/panel/server_detail?id={server_id}&subpage=files")
return return
@ -237,14 +237,14 @@ class FileHandler(BaseHandler):
server_id = self.get_argument("id", None) server_id = self.get_argument("id", None)
permissions = { permissions = {
"Commands": Enum_Permissions_Server.Commands, "Commands": EnumPermissionsServer.COMMANDS,
"Terminal": Enum_Permissions_Server.Terminal, "Terminal": EnumPermissionsServer.TERMINAL,
"Logs": Enum_Permissions_Server.Logs, "Logs": EnumPermissionsServer.LOGS,
"Schedule": Enum_Permissions_Server.Schedule, "Schedule": EnumPermissionsServer.SCHEDULE,
"Backup": Enum_Permissions_Server.Backup, "Backup": EnumPermissionsServer.BACKUP,
"Files": Enum_Permissions_Server.Files, "Files": EnumPermissionsServer.FILES,
"Config": Enum_Permissions_Server.Config, "Config": EnumPermissionsServer.CONFIG,
"Players": Enum_Permissions_Server.Players, "Players": EnumPermissionsServer.PLAYERS,
} }
user_perms = self.controller.server_perms.get_user_id_permissions_list( user_perms = self.controller.server_perms.get_user_id_permissions_list(
exec_user["user_id"], server_id exec_user["user_id"], server_id
@ -325,14 +325,14 @@ class FileHandler(BaseHandler):
server_id = self.get_argument("id", None) server_id = self.get_argument("id", None)
permissions = { permissions = {
"Commands": Enum_Permissions_Server.Commands, "Commands": EnumPermissionsServer.COMMANDS,
"Terminal": Enum_Permissions_Server.Terminal, "Terminal": EnumPermissionsServer.TERMINAL,
"Logs": Enum_Permissions_Server.Logs, "Logs": EnumPermissionsServer.LOGS,
"Schedule": Enum_Permissions_Server.Schedule, "Schedule": EnumPermissionsServer.SCHEDULE,
"Backup": Enum_Permissions_Server.Backup, "Backup": EnumPermissionsServer.BACKUP,
"Files": Enum_Permissions_Server.Files, "Files": EnumPermissionsServer.FILES,
"Config": Enum_Permissions_Server.Config, "Config": EnumPermissionsServer.CONFIG,
"Players": Enum_Permissions_Server.Players, "Players": EnumPermissionsServer.PLAYERS,
} }
user_perms = self.controller.server_perms.get_user_id_permissions_list( user_perms = self.controller.server_perms.get_user_id_permissions_list(
exec_user["user_id"], server_id exec_user["user_id"], server_id
@ -436,14 +436,14 @@ class FileHandler(BaseHandler):
server_id = self.get_argument("id", None) server_id = self.get_argument("id", None)
permissions = { permissions = {
"Commands": Enum_Permissions_Server.Commands, "Commands": EnumPermissionsServer.COMMANDS,
"Terminal": Enum_Permissions_Server.Terminal, "Terminal": EnumPermissionsServer.TERMINAL,
"Logs": Enum_Permissions_Server.Logs, "Logs": EnumPermissionsServer.LOGS,
"Schedule": Enum_Permissions_Server.Schedule, "Schedule": EnumPermissionsServer.SCHEDULE,
"Backup": Enum_Permissions_Server.Backup, "Backup": EnumPermissionsServer.BACKUP,
"Files": Enum_Permissions_Server.Files, "Files": EnumPermissionsServer.FILES,
"Config": Enum_Permissions_Server.Config, "Config": EnumPermissionsServer.CONFIG,
"Players": Enum_Permissions_Server.Players, "Players": EnumPermissionsServer.PLAYERS,
} }
user_perms = self.controller.server_perms.get_user_id_permissions_list( user_perms = self.controller.server_perms.get_user_id_permissions_list(
exec_user["user_id"], server_id exec_user["user_id"], server_id

View File

@ -17,9 +17,9 @@ from tornado import iostream
from tzlocal import get_localzone from tzlocal import get_localzone
from cron_validator import CronValidator from cron_validator import CronValidator
from app.classes.models.server_permissions import Enum_Permissions_Server from app.classes.models.server_permissions import EnumPermissionsServer
from app.classes.models.crafty_permissions import Enum_Permissions_Crafty from app.classes.models.crafty_permissions import EnumPermissionsCrafty
from app.classes.models.management import helpers_management from app.classes.models.management import HelpersManagement
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
from app.classes.web.base_handler import BaseHandler from app.classes.web.base_handler import BaseHandler
@ -185,10 +185,10 @@ class PanelHandler(BaseHandler):
) )
page_data["num_players"] = total_players page_data["num_players"] = total_players
for s in page_data["servers"]: for server in page_data["servers"]:
try: try:
data = json.loads(s["int_ping_results"]) data = json.loads(server["int_ping_results"])
s["int_ping_results"] = data server["int_ping_results"] = data
except Exception as e: except Exception as e:
logger.error(f"Failed server data for page with error: {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_role": exec_user_role,
"user_crafty_permissions": exec_user_crafty_permissions, "user_crafty_permissions": exec_user_crafty_permissions,
"crafty_permissions": { "crafty_permissions": {
"Server_Creation": Enum_Permissions_Crafty.Server_Creation, "Server_Creation": EnumPermissionsCrafty.SERVER_CREATION,
"User_Config": Enum_Permissions_Crafty.User_Config, "User_Config": EnumPermissionsCrafty.USER_CONFIG,
"Roles_Config": Enum_Permissions_Crafty.Roles_Config, "Roles_Config": EnumPermissionsCrafty.ROLES_CONFIG,
}, },
"server_stats": { "server_stats": {
"total": len(defined_servers), "total": len(defined_servers),
@ -285,7 +285,7 @@ class PanelHandler(BaseHandler):
"error": error, "error": error,
"time": formatted_time, "time": formatted_time,
"lang": self.controller.users.get_user_lang_by_id(exec_user["user_id"]), "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"]) self.controller.users.get_user_lang_by_id(exec_user["user_id"])
), ),
"super_user": superuser, "super_user": superuser,
@ -307,8 +307,10 @@ class PanelHandler(BaseHandler):
# Get grvatar hash for profile pictures # Get grvatar hash for profile pictures
if exec_user["email"] != "default@example.com" or "": if exec_user["email"] != "default@example.com" or "":
g = libgravatar.Gravatar(libgravatar.sanitize_email(exec_user["email"])) gravatar = libgravatar.Gravatar(
url = g.get_image( libgravatar.sanitize_email(exec_user["email"])
)
url = gravatar.get_image(
size=80, size=80,
default="404", default="404",
force_default=False, force_default=False,
@ -498,14 +500,14 @@ class PanelHandler(BaseHandler):
) )
page_data["active_link"] = subpage page_data["active_link"] = subpage
page_data["permissions"] = { page_data["permissions"] = {
"Commands": Enum_Permissions_Server.Commands, "Commands": EnumPermissionsServer.COMMANDS,
"Terminal": Enum_Permissions_Server.Terminal, "Terminal": EnumPermissionsServer.TERMINAL,
"Logs": Enum_Permissions_Server.Logs, "Logs": EnumPermissionsServer.LOGS,
"Schedule": Enum_Permissions_Server.Schedule, "Schedule": EnumPermissionsServer.SCHEDULE,
"Backup": Enum_Permissions_Server.Backup, "Backup": EnumPermissionsServer.BACKUP,
"Files": Enum_Permissions_Server.Files, "Files": EnumPermissionsServer.FILES,
"Config": Enum_Permissions_Server.Config, "Config": EnumPermissionsServer.CONFIG,
"Players": Enum_Permissions_Server.Players, "Players": EnumPermissionsServer.PLAYERS,
} }
page_data[ page_data[
"user_permissions" "user_permissions"
@ -581,7 +583,7 @@ class PanelHandler(BaseHandler):
"/panel/error?error=Unauthorized access To Schedules" "/panel/error?error=Unauthorized access To Schedules"
) )
return return
page_data["schedules"] = helpers_management.get_schedules_by_server( page_data["schedules"] = HelpersManagement.get_schedules_by_server(
server_id server_id
) )
@ -767,7 +769,7 @@ class PanelHandler(BaseHandler):
page_data["user"]["roles"] = set() page_data["user"]["roles"] = set()
page_data["user"]["hints"] = True 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( self.redirect(
"/panel/error?error=Unauthorized access: not a user editor" "/panel/error?error=Unauthorized access: not a user editor"
) )
@ -806,7 +808,7 @@ class PanelHandler(BaseHandler):
elif page == "add_schedule": elif page == "add_schedule":
server_id = self.get_argument("id", None) 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 server_id
) )
page_data["get_players"] = lambda: self.controller.stats.get_server_players( 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["active_link"] = "schedules"
page_data["permissions"] = { page_data["permissions"] = {
"Commands": Enum_Permissions_Server.Commands, "Commands": EnumPermissionsServer.COMMANDS,
"Terminal": Enum_Permissions_Server.Terminal, "Terminal": EnumPermissionsServer.TERMINAL,
"Logs": Enum_Permissions_Server.Logs, "Logs": EnumPermissionsServer.LOGS,
"Schedule": Enum_Permissions_Server.Schedule, "Schedule": EnumPermissionsServer.SCHEDULE,
"Backup": Enum_Permissions_Server.Backup, "Backup": EnumPermissionsServer.BACKUP,
"Files": Enum_Permissions_Server.Files, "Files": EnumPermissionsServer.FILES,
"Config": Enum_Permissions_Server.Config, "Config": EnumPermissionsServer.CONFIG,
"Players": Enum_Permissions_Server.Players, "Players": EnumPermissionsServer.PLAYERS,
} }
page_data[ page_data[
"user_permissions" "user_permissions"
@ -854,7 +856,7 @@ class PanelHandler(BaseHandler):
page_data["schedule"]["difficulty"] = "basic" page_data["schedule"]["difficulty"] = "basic"
page_data["schedule"]["interval_type"] = "days" 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: if not superuser:
self.redirect("/panel/error?error=Unauthorized access To Schedules") self.redirect("/panel/error?error=Unauthorized access To Schedules")
return return
@ -863,7 +865,7 @@ class PanelHandler(BaseHandler):
elif page == "edit_schedule": elif page == "edit_schedule":
server_id = self.get_argument("id", None) 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 server_id
) )
sch_id = self.get_argument("sch_id", None) sch_id = self.get_argument("sch_id", None)
@ -873,14 +875,14 @@ class PanelHandler(BaseHandler):
) )
page_data["active_link"] = "schedules" page_data["active_link"] = "schedules"
page_data["permissions"] = { page_data["permissions"] = {
"Commands": Enum_Permissions_Server.Commands, "Commands": EnumPermissionsServer.COMMANDS,
"Terminal": Enum_Permissions_Server.Terminal, "Terminal": EnumPermissionsServer.TERMINAL,
"Logs": Enum_Permissions_Server.Logs, "Logs": EnumPermissionsServer.LOGS,
"Schedule": Enum_Permissions_Server.Schedule, "Schedule": EnumPermissionsServer.SCHEDULE,
"Backup": Enum_Permissions_Server.Backup, "Backup": EnumPermissionsServer.BACKUP,
"Files": Enum_Permissions_Server.Files, "Files": EnumPermissionsServer.FILES,
"Config": Enum_Permissions_Server.Config, "Config": EnumPermissionsServer.CONFIG,
"Players": Enum_Permissions_Server.Players, "Players": EnumPermissionsServer.PLAYERS,
} }
page_data[ page_data[
"user_permissions" "user_permissions"
@ -933,7 +935,7 @@ class PanelHandler(BaseHandler):
if sch_id is None or server_id is None: if sch_id is None or server_id is None:
self.redirect("/panel/error?error=Invalid server ID or Schedule ID") 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: if not superuser:
self.redirect("/panel/error?error=Unauthorized access To Schedules") self.redirect("/panel/error?error=Unauthorized access To Schedules")
return return
@ -985,9 +987,7 @@ class PanelHandler(BaseHandler):
if user_id is None: if user_id is None:
self.redirect("/panel/error?error=Invalid User ID") self.redirect("/panel/error?error=Invalid User ID")
return return
elif ( elif EnumPermissionsCrafty.USER_CONFIG not in exec_user_crafty_permissions:
Enum_Permissions_Crafty.User_Config not in exec_user_crafty_permissions
):
if str(user_id) != str(exec_user["user_id"]): if str(user_id) != str(exec_user["user_id"]):
self.redirect( self.redirect(
"/panel/error?error=Unauthorized access: not a user editor" "/panel/error?error=Unauthorized access: not a user editor"
@ -1029,7 +1029,7 @@ class PanelHandler(BaseHandler):
if ( if (
not superuser not superuser
and Enum_Permissions_Crafty.User_Config and EnumPermissionsCrafty.USER_CONFIG
not in exec_user_crafty_permissions not in exec_user_crafty_permissions
): ):
self.redirect("/panel/error?error=Unauthorized access: not superuser") self.redirect("/panel/error?error=Unauthorized access: not superuser")
@ -1075,7 +1075,7 @@ class PanelHandler(BaseHandler):
page_data["user-roles"] = user_roles page_data["user-roles"] = user_roles
page_data["users"] = self.controller.users.get_all_users() 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( self.redirect(
"/panel/error?error=Unauthorized access: not a role editor" "/panel/error?error=Unauthorized access: not a role editor"
) )
@ -1103,7 +1103,7 @@ class PanelHandler(BaseHandler):
page_data["user-roles"] = user_roles page_data["user-roles"] = user_roles
page_data["users"] = self.controller.users.get_all_users() 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( self.redirect(
"/panel/error?error=Unauthorized access: not a role editor" "/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") self.redirect(f"/panel/server_detail?id={server_id}&subpage=files")
elif page == "download_support_package": 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. # We'll reset the support path for this user now.
self.controller.users.set_support_path(exec_user["user_id"], "") self.controller.users.set_support_path(exec_user["user_id"], "")
@ -1174,8 +1174,8 @@ class PanelHandler(BaseHandler):
"Content-Disposition", "attachment; filename=" + "support_logs.zip" "Content-Disposition", "attachment; filename=" + "support_logs.zip"
) )
chunk_size = 1024 * 1024 * 4 # 4 MiB chunk_size = 1024 * 1024 * 4 # 4 MiB
if tempZipStorage != "": if temp_zip_storage != "":
with open(tempZipStorage, "rb") as f: with open(temp_zip_storage, "rb") as f:
while True: while True:
chunk = f.read(chunk_size) chunk = f.read(chunk_size)
if not chunk: if not chunk:
@ -1230,14 +1230,14 @@ class PanelHandler(BaseHandler):
server_id = self.get_argument("id", None) server_id = self.get_argument("id", None)
permissions = { permissions = {
"Commands": Enum_Permissions_Server.Commands, "Commands": EnumPermissionsServer.COMMANDS,
"Terminal": Enum_Permissions_Server.Terminal, "Terminal": EnumPermissionsServer.TERMINAL,
"Logs": Enum_Permissions_Server.Logs, "Logs": EnumPermissionsServer.LOGS,
"Schedule": Enum_Permissions_Server.Schedule, "Schedule": EnumPermissionsServer.SCHEDULE,
"Backup": Enum_Permissions_Server.Backup, "Backup": EnumPermissionsServer.BACKUP,
"Files": Enum_Permissions_Server.Files, "Files": EnumPermissionsServer.FILES,
"Config": Enum_Permissions_Server.Config, "Config": EnumPermissionsServer.CONFIG,
"Players": Enum_Permissions_Server.Players, "Players": EnumPermissionsServer.PLAYERS,
} }
exec_user_role = set() exec_user_role = set()
if superuser: if superuser:
@ -1758,7 +1758,7 @@ class PanelHandler(BaseHandler):
superuser = False superuser = False
if not exec_user["superuser"]: if not exec_user["superuser"]:
if ( if (
Enum_Permissions_Crafty.User_Config EnumPermissionsCrafty.USER_CONFIG
not in exec_user_crafty_permissions not in exec_user_crafty_permissions
): ):
if str(user_id) != str(exec_user["user_id"]): if str(user_id) != str(exec_user["user_id"]):
@ -1926,7 +1926,7 @@ class PanelHandler(BaseHandler):
else: else:
new_superuser = False 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( self.redirect(
"/panel/error?error=Unauthorized access: not a user editor" "/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_id = bleach.clean(self.get_argument("id", None))
role_name = bleach.clean(self.get_argument("role_name", 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( self.redirect(
"/panel/error?error=Unauthorized access: not a role editor" "/panel/error?error=Unauthorized access: not a role editor"
) )
@ -2017,7 +2017,7 @@ class PanelHandler(BaseHandler):
elif page == "add_role": elif page == "add_role":
role_name = bleach.clean(self.get_argument("role_name", 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( self.redirect(
"/panel/error?error=Unauthorized access: not a role editor" "/panel/error?error=Unauthorized access: not a role editor"
) )
@ -2057,7 +2057,7 @@ class PanelHandler(BaseHandler):
self.set_status(404) self.set_status(404)
page_data = { page_data = {
"lang": self.helper.get_setting("language"), "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( self.render(
"public/404.html", translate=self.translator.translate, data=page_data "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(), "hosts_data": self.controller.management.get_latest_hosts_stats(),
"show_contribute": self.helper.get_setting("show_contribute_link", True), "show_contribute": self.helper.get_setting("show_contribute_link", True),
"lang": self.controller.users.get_user_lang_by_id(exec_user["user_id"]), "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"]) self.controller.users.get_user_lang_by_id(exec_user["user_id"])
), ),
} }

View File

@ -2,7 +2,7 @@ import logging
import bleach import bleach
from app.classes.shared.helpers import Helpers 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 from app.classes.web.base_handler import BaseHandler
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -37,7 +37,7 @@ class PublicHandler(BaseHandler):
"version": self.helper.get_version_string(), "version": self.helper.get_version_string(),
"error": error, "error": error,
"lang": self.helper.get_setting("language"), "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": "", "query": "",
} }
if self.request.query: if self.request.query:
@ -86,7 +86,7 @@ class PublicHandler(BaseHandler):
"version": self.helper.get_version_string(), "version": self.helper.get_version_string(),
"error": error, "error": error,
"lang": self.helper.get_setting("language"), "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": "", "query": "",
} }
if self.request.query: if self.request.query:
@ -103,8 +103,8 @@ class PublicHandler(BaseHandler):
# pylint: disable=no-member # pylint: disable=no-member
try: try:
user_id = helper_users.get_user_id_by_name(entered_username.lower()) user_id = HelperUsers.get_user_id_by_name(entered_username.lower())
user_data = helper_users.get_user_model(user_id) user_data = HelperUsers.get_user_model(user_id)
except: except:
error_msg = "Incorrect username or password. Please try again." error_msg = "Incorrect username or password. Please try again."
# self.clear_cookie("user") # self.clear_cookie("user")

View File

@ -7,7 +7,7 @@ import bleach
import libgravatar import libgravatar
import requests 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.helpers import Helpers
from app.classes.shared.file_helpers import FileHelpers from app.classes.shared.file_helpers import FileHelpers
from app.classes.web.base_handler import BaseHandler from app.classes.web.base_handler import BaseHandler
@ -18,8 +18,11 @@ logger = logging.getLogger(__name__)
class ServerHandler(BaseHandler): class ServerHandler(BaseHandler):
@tornado.web.authenticated @tornado.web.authenticated
def get(self, page): 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"] superuser = exec_user["superuser"]
if api_key is not None: if api_key is not None:
superuser = superuser and api_key.superuser superuser = superuser and api_key.superuser
@ -58,9 +61,9 @@ class ServerHandler(BaseHandler):
"roles": list_roles, "roles": list_roles,
"user_crafty_permissions": exec_user_crafty_permissions, "user_crafty_permissions": exec_user_crafty_permissions,
"crafty_permissions": { "crafty_permissions": {
"Server_Creation": Enum_Permissions_Crafty.Server_Creation, "Server_Creation": EnumPermissionsCrafty.SERVER_CREATION,
"User_Config": Enum_Permissions_Crafty.User_Config, "User_Config": EnumPermissionsCrafty.USER_CONFIG,
"Roles_Config": Enum_Permissions_Crafty.Roles_Config, "Roles_Config": EnumPermissionsCrafty.ROLES_CONFIG,
}, },
"server_stats": { "server_stats": {
"total": len(self.controller.list_defined_servers()), "total": len(self.controller.list_defined_servers()),
@ -74,7 +77,7 @@ class ServerHandler(BaseHandler):
"menu_servers": defined_servers, "menu_servers": defined_servers,
"show_contribute": self.helper.get_setting("show_contribute_link", True), "show_contribute": self.helper.get_setting("show_contribute_link", True),
"lang": self.controller.users.get_user_lang_by_id(exec_user["user_id"]), "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"]) self.controller.users.get_user_lang_by_id(exec_user["user_id"])
), ),
"api_key": { "api_key": {
@ -95,8 +98,10 @@ class ServerHandler(BaseHandler):
rating = "g" rating = "g"
if exec_user["email"] != "default@example.com" or "": if exec_user["email"] != "default@example.com" or "":
g = libgravatar.Gravatar(libgravatar.sanitize_email(exec_user["email"])) gravatar = libgravatar.Gravatar(
url = g.get_image( libgravatar.sanitize_email(exec_user["email"])
)
url = gravatar.get_image(
size=80, size=80,
default="404", default="404",
force_default=False, force_default=False,
@ -155,8 +160,7 @@ class ServerHandler(BaseHandler):
@tornado.web.authenticated @tornado.web.authenticated
def post(self, page): 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"] superuser = exec_user["superuser"]
if api_key is not None: if api_key is not None:
superuser = superuser and api_key.superuser superuser = superuser and api_key.superuser
@ -167,7 +171,7 @@ class ServerHandler(BaseHandler):
"user_data": exec_user, "user_data": exec_user,
"show_contribute": self.helper.get_setting("show_contribute_link", True), "show_contribute": self.helper.get_setting("show_contribute_link", True),
"lang": self.controller.users.get_user_lang_by_id(exec_user["user_id"]), "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"]) 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 server_type, server_version = server_parts
# TODO: add server type check here and call the correct server # TODO: add server type check here and call the correct server
# add functions if not a jar # 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( new_server_id = self.controller.create_jar_server(
server_type, server_version, server_name, min_mem, max_mem, port server_type, server_version, server_name, min_mem, max_mem, port
) )
@ -445,7 +448,6 @@ class ServerHandler(BaseHandler):
server_type, server_version = server_parts server_type, server_version = server_parts
# TODO: add server type check here and call the correct server # TODO: add server type check here and call the correct server
# add functions if not a jar # 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( new_server_id = self.controller.create_jar_server(
server_type, server_version, server_name, min_mem, max_mem, port server_type, server_version, server_name, min_mem, max_mem, port
) )

View File

@ -9,7 +9,7 @@ class StatusHandler(BaseHandler):
def get(self): def get(self):
page_data = {} page_data = {}
page_data["lang"] = self.helper.get_setting("language") 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") self.helper.get_setting("language")
) )
page_data["servers"] = self.controller.servers.get_all_servers_stats() page_data["servers"] = self.controller.servers.get_all_servers_stats()

View File

@ -44,8 +44,8 @@ logger = logging.getLogger(__name__)
class Webserver: class Webserver:
def __init__(self, helper, controller, tasks_manager): def __init__(self, helper, controller, tasks_manager):
self.ioloop = None self.ioloop = None
self.HTTP_Server = None self.http_server = None
self.HTTPS_Server = None self.https_server = None
self.helper = helper self.helper = helper
self.controller = controller self.controller = controller
self.tasks_manager = tasks_manager self.tasks_manager = tasks_manager
@ -177,7 +177,7 @@ class Webserver:
static_handler_class=CustomStaticHandler, static_handler_class=CustomStaticHandler,
serve_traceback=debug_errors, serve_traceback=debug_errors,
) )
HTTPhanders = [ http_handers = [
(r"/", HTTPHandler, handler_args), (r"/", HTTPHandler, handler_args),
(r"/public/(.*)", HTTPHandlerPage, handler_args), (r"/public/(.*)", HTTPHandlerPage, handler_args),
(r"/panel/(.*)", HTTPHandlerPage, handler_args), (r"/panel/(.*)", HTTPHandlerPage, handler_args),
@ -188,8 +188,8 @@ class Webserver:
(r"/ws", HTTPHandlerPage, handler_args), (r"/ws", HTTPHandlerPage, handler_args),
(r"/upload", HTTPHandlerPage, handler_args), (r"/upload", HTTPHandlerPage, handler_args),
] ]
HTTPapp = tornado.web.Application( http_app = tornado.web.Application(
HTTPhanders, http_handers,
template_path=os.path.join(self.helper.webroot, "templates"), template_path=os.path.join(self.helper.webroot, "templates"),
static_path=os.path.join(self.helper.webroot, "static"), static_path=os.path.join(self.helper.webroot, "static"),
debug=debug_errors, debug=debug_errors,
@ -202,11 +202,11 @@ class Webserver:
serve_traceback=debug_errors, serve_traceback=debug_errors,
) )
self.HTTP_Server = tornado.httpserver.HTTPServer(HTTPapp) self.http_server = tornado.httpserver.HTTPServer(http_app)
self.HTTP_Server.listen(http_port) self.http_server.listen(http_port)
self.HTTPS_Server = tornado.httpserver.HTTPServer(app, ssl_options=cert_objects) self.https_server = tornado.httpserver.HTTPServer(app, ssl_options=cert_objects)
self.HTTPS_Server.listen(https_port) self.https_server.listen(https_port)
logger.info( logger.info(
f"https://{Helpers.get_local_ip()}:{https_port} " f"https://{Helpers.get_local_ip()}:{https_port} "
@ -226,7 +226,7 @@ class Webserver:
logger.info("Shutting Down Web Server") logger.info("Shutting Down Web Server")
Console.info("Shutting Down Web Server") Console.info("Shutting Down Web Server")
self.ioloop.stop() self.ioloop.stop()
self.HTTP_Server.stop() self.http_server.stop()
self.HTTPS_Server.stop() self.https_server.stop()
logger.info("Web Server Stopped") logger.info("Web Server Stopped")
Console.info("Web Server Stopped") Console.info("Web Server Stopped")

View File

@ -5,7 +5,7 @@ import tornado.web
import tornado.options import tornado.options
import tornado.httpserver 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.console import Console
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
from app.classes.shared.main_controller import Controller from app.classes.shared.main_controller import Controller
@ -40,10 +40,10 @@ class UploadHandler(BaseHandler):
user_id = exec_user["user_id"] user_id = exec_user["user_id"]
stream_size_value = self.helper.get_setting("stream_size_GB") 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")) 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( logger.error(
f"User with ID {user_id} attempted to upload a file that" f"User with ID {user_id} attempted to upload a file that"
f" exceeded the max body size." f" exceeded the max body size."
@ -91,7 +91,7 @@ class UploadHandler(BaseHandler):
Console.warning("Server ID not found in upload handler call") Console.warning("Server ID not found in upload handler call")
self.do_upload = False 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( logger.warning(
f"User {user_id} tried to upload a file to " f"User {user_id} tried to upload a file to "
f"{server_id} without permissions!" f"{server_id} without permissions!"
@ -137,7 +137,7 @@ class UploadHandler(BaseHandler):
logger.error(f"Upload failed with error: {e}") logger.error(f"Upload failed with error: {e}")
self.do_upload = False self.do_upload = False
# If max_body_size is not set, you cannot upload files > 100MB # 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): def post(self):
logger.info("Upload completed") logger.info("Upload completed")

View File

@ -17,8 +17,9 @@ class WebSocketHelper:
def remove_client(self, client): def remove_client(self, client):
self.clients.remove(client) self.clients.remove(client)
# pylint: disable=no-self-use def send_message(
def send_message(self, client, event_type: str, data): self, client, event_type: str, data
): # pylint: disable=no-self-use
if client.check_auth(): if client.check_auth():
message = str(json.dumps({"event": event_type, "data": data})) message = str(json.dumps({"event": event_type, "data": data}))
client.write_message_helper(message) client.write_message_helper(message)

14
main.py
View File

@ -6,13 +6,13 @@ import argparse
import logging.config import logging.config
import signal import signal
import peewee 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.console import Console
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
console = Console() console = Console()
helper = Helpers() helper = Helpers()
if helper.checkRoot(): if helper.check_root():
Console.critical( Console.critical(
"Root detected. Root/Admin access denied. " "Root detected. Root/Admin access denied. "
"Run Crafty again with non-elevated permissions." "Run Crafty again with non-elevated permissions."
@ -23,7 +23,7 @@ if helper.checkRoot():
# pylint: disable=wrong-import-position # pylint: disable=wrong-import-position
try: try:
from app.classes.models.base_model import database_proxy 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.tasks import TasksManager
from app.classes.shared.main_controller import Controller from app.classes.shared.main_controller import Controller
from app.classes.shared.migration import MigrationManager from app.classes.shared.migration import MigrationManager
@ -114,11 +114,11 @@ if __name__ == "__main__":
migration_manager.up() # Automatically runs migrations migration_manager.up() # Automatically runs migrations
# do our installer stuff # do our installer stuff
user_helper = helper_users(database, helper) user_helper = HelperUsers(database, helper)
installer = db_builder(database, helper, user_helper) installer = DatabaseBuilder(database, helper, user_helper)
fresh_install = installer.is_fresh_install() FRESH_INSTALL = installer.is_fresh_install()
if fresh_install: if FRESH_INSTALL:
Console.debug("Fresh install detected") Console.debug("Fresh install detected")
Console.warning( Console.warning(
f"We have detected a fresh install. Please be sure to forward " f"We have detected a fresh install. Please be sure to forward "