diff --git a/app/classes/controllers/crafty_perms_controller.py b/app/classes/controllers/crafty_perms_controller.py
index 4f50d0bb..f47324b2 100644
--- a/app/classes/controllers/crafty_perms_controller.py
+++ b/app/classes/controllers/crafty_perms_controller.py
@@ -36,15 +36,19 @@ class Crafty_Perms_Controller:
@staticmethod
def can_add_user(): # Add back argument 'user_id' when you work on this
- # TODO: Complete if we need a User Addition limit
- # return crafty_permissions.can_add_in_crafty(user_id, Enum_Permissions_Crafty.User_Config)
return True
+ # TODO: Complete if we need a User Addition limit
+ # return crafty_permissions.can_add_in_crafty(
+ # user_id, Enum_Permissions_Crafty.User_Config
+ # )
@staticmethod
def can_add_role(): # Add back argument 'user_id' when you work on this
- # TODO: Complete if we need a Role Addition limit
- # return crafty_permissions.can_add_in_crafty(user_id, Enum_Permissions_Crafty.Roles_Config)
return True
+ # TODO: Complete if we need a Role Addition limit
+ # return crafty_permissions.can_add_in_crafty(
+ # user_id, Enum_Permissions_Crafty.Roles_Config
+ # )
@staticmethod
def list_all_crafty_permissions_quantity_limits():
diff --git a/app/classes/controllers/management_controller.py b/app/classes/controllers/management_controller.py
index f2d62d75..f591dbfc 100644
--- a/app/classes/controllers/management_controller.py
+++ b/app/classes/controllers/management_controller.py
@@ -8,16 +8,16 @@ logger = logging.getLogger(__name__)
class Management_Controller:
- # ************************************************************************************************
+ # **********************************************************************************
# Host_Stats Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_latest_hosts_stats():
return management_helper.get_latest_hosts_stats()
- # ************************************************************************************************
+ # **********************************************************************************
# Commands Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_unactioned_commands():
return management_helper.get_unactioned_commands()
@@ -39,9 +39,9 @@ class Management_Controller:
def mark_command_complete(command_id=None):
return management_helper.mark_command_complete(command_id)
- # ************************************************************************************************
+ # **********************************************************************************
# Audit_Log Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_actity_log():
return management_helper.get_actity_log()
@@ -58,9 +58,9 @@ class Management_Controller:
user_name, user_id, server_id, log_msg, source_ip
)
- # ************************************************************************************************
+ # **********************************************************************************
# Schedules Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def create_scheduled_task(
server_id,
@@ -115,9 +115,9 @@ class Management_Controller:
def get_schedules_enabled():
return management_helper.get_schedules_enabled()
- # ************************************************************************************************
+ # **********************************************************************************
# Backups Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_backup_config(server_id):
return management_helper.get_backup_config(server_id)
diff --git a/app/classes/controllers/roles_controller.py b/app/classes/controllers/roles_controller.py
index 224995df..f3bcbad8 100644
--- a/app/classes/controllers/roles_controller.py
+++ b/app/classes/controllers/roles_controller.py
@@ -45,7 +45,8 @@ class Roles_Controller:
server_permissions.get_or_create(role_id, server, permissions_mask)
for server in base_data["servers"]:
server_permissions.update_role_permission(role_id, server, permissions_mask)
- # TODO: This is horribly inefficient and we should be using bulk queries but im going for functionality at this point
+ # TODO: This is horribly inefficient and we should be using bulk queries
+ # but im going for functionality at this point
server_permissions.delete_roles_permissions(role_id, removed_servers)
if up_data:
roles_helper.update_role(role_id, up_data)
diff --git a/app/classes/controllers/server_perms_controller.py b/app/classes/controllers/server_perms_controller.py
index 931f4f1e..9da02d08 100644
--- a/app/classes/controllers/server_perms_controller.py
+++ b/app/classes/controllers/server_perms_controller.py
@@ -51,11 +51,11 @@ class Server_Perms_Controller:
int(role.role_id), int(old_server_id)
),
)
- # server_permissions.add_role_server(new_server_id, role.role_id, '00001000')
+ # server_permissions.add_role_server(new_server_id, role.role_id,"00001000")
- # ************************************************************************************************
+ # **********************************************************************************
# Servers Permissions Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_permissions_mask(role_id, server_id):
return server_permissions.get_permissions_mask(role_id, server_id)
diff --git a/app/classes/controllers/servers_controller.py b/app/classes/controllers/servers_controller.py
index cfec8375..b7c09935 100644
--- a/app/classes/controllers/servers_controller.py
+++ b/app/classes/controllers/servers_controller.py
@@ -17,9 +17,9 @@ logger = logging.getLogger(__name__)
class Servers_Controller:
- # ************************************************************************************************
+ # **********************************************************************************
# Generic Servers Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def create_server(
name: str,
@@ -81,9 +81,9 @@ class Servers_Controller:
def get_server_data_by_id(server_id):
return servers_helper.get_server_data_by_id(server_id)
- # ************************************************************************************************
+ # **********************************************************************************
# Servers Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_all_defined_servers():
return servers_helper.get_all_defined_servers()
@@ -157,9 +157,9 @@ class Servers_Controller:
def get_server_friendly_name(server_id):
return servers_helper.get_server_friendly_name(server_id)
- # ************************************************************************************************
+ # **********************************************************************************
# Servers_Stats Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_server_stats_by_id(server_id):
return servers_helper.get_server_stats_by_id(server_id)
@@ -218,9 +218,9 @@ class Servers_Controller:
def get_update_status(server_id):
return servers_helper.get_update_status(server_id)
- # ************************************************************************************************
+ # **********************************************************************************
# Servers Helpers Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_banned_players(server_id):
stats = servers_helper.get_server_stats_by_id(server_id)
diff --git a/app/classes/controllers/users_controller.py b/app/classes/controllers/users_controller.py
index af590046..933942c6 100644
--- a/app/classes/controllers/users_controller.py
+++ b/app/classes/controllers/users_controller.py
@@ -14,9 +14,9 @@ logger = logging.getLogger(__name__)
class Users_Controller:
- # ************************************************************************************************
+ # **********************************************************************************
# Users Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_all_users():
return users_helper.get_all_users()
@@ -163,9 +163,9 @@ class Users_Controller:
_, user = authentication.check(token)
return user
- # ************************************************************************************************
+ # **********************************************************************************
# User Roles Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_user_roles_id(user_id):
@@ -187,9 +187,9 @@ class Users_Controller:
def user_role_query(user_id):
return users_helper.user_role_query(user_id)
- # ************************************************************************************************
+ # **********************************************************************************
# Api Keys Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_user_api_keys(user_id: str):
diff --git a/app/classes/minecraft/server_props.py b/app/classes/minecraft/server_props.py
index c70652de..84b8d039 100644
--- a/app/classes/minecraft/server_props.py
+++ b/app/classes/minecraft/server_props.py
@@ -1,66 +1,67 @@
-import pprint
-import os
-
-
-class ServerProps:
- def __init__(self, filepath):
- self.filepath = filepath
- self.props = self._parse()
-
- def _parse(self):
- """Loads and parses the file specified in self.filepath"""
- with open(self.filepath, encoding="utf-8") as fp:
- line = fp.readline()
- d = {}
- if os.path.exists(".header"):
- os.remove(".header")
- while line:
- if "#" != line[0]:
- s = line
- s1 = s[: s.find("=")]
- if "\n" in s:
- s2 = s[s.find("=") + 1 : s.find("\n")]
- else:
- s2 = s[s.find("=") + 1 :]
- d[s1] = s2
- else:
- with open(".header", "a+", encoding="utf-8") as h:
- h.write(line)
- line = fp.readline()
- return d
-
- def print(self):
- """Prints the properties dictionary (using pprint)"""
- pprint.pprint(self.props)
-
- def get(self):
- """Returns the properties dictionary"""
- return self.props
-
- def update(self, key, val):
- """Updates property in the properties dictionary [ update("pvp", "true") ] and returns boolean condition"""
- if key in self.props.keys():
- self.props[key] = val
- return True
- else:
- return False
-
- def save(self):
- """Writes to the new file"""
- with open(self.filepath, "a+", encoding="utf-8") as f:
- f.truncate(0)
- with open(".header", encoding="utf-8") as header:
- line = header.readline()
- while line:
- f.write(line)
- line = header.readline()
- header.close()
- for key, value in self.props.items():
- f.write(key + "=" + value + "\n")
- if os.path.exists(".header"):
- os.remove(".header")
-
- @staticmethod
- def cleanup():
- if os.path.exists(".header"):
- os.remove(".header")
+import pprint
+import os
+
+
+class ServerProps:
+ def __init__(self, filepath):
+ self.filepath = filepath
+ self.props = self._parse()
+
+ def _parse(self):
+ # Loads and parses the file specified in self.filepath
+ with open(self.filepath, encoding="utf-8") as fp:
+ line = fp.readline()
+ d = {}
+ if os.path.exists(".header"):
+ os.remove(".header")
+ while line:
+ if "#" != line[0]:
+ s = line
+ s1 = s[: s.find("=")]
+ if "\n" in s:
+ s2 = s[s.find("=") + 1 : s.find("\n")]
+ else:
+ s2 = s[s.find("=") + 1 :]
+ d[s1] = s2
+ else:
+ with open(".header", "a+", encoding="utf-8") as h:
+ h.write(line)
+ line = fp.readline()
+ return d
+
+ def print(self):
+ # Prints the properties dictionary (using pprint)
+ pprint.pprint(self.props)
+
+ def get(self):
+ # Returns the properties dictionary
+ return self.props
+
+ def update(self, key, val):
+ # Updates property in the properties dictionary [ update("pvp", "true") ]
+ # and returns boolean condition
+ if key in self.props.keys():
+ self.props[key] = val
+ return True
+ else:
+ return False
+
+ def save(self):
+ # Writes to the new file
+ with open(self.filepath, "a+", encoding="utf-8") as f:
+ f.truncate(0)
+ with open(".header", encoding="utf-8") as header:
+ line = header.readline()
+ while line:
+ f.write(line)
+ line = header.readline()
+ header.close()
+ for key, value in self.props.items():
+ f.write(key + "=" + value + "\n")
+ if os.path.exists(".header"):
+ os.remove(".header")
+
+ @staticmethod
+ def cleanup():
+ if os.path.exists(".header"):
+ os.remove(".header")
diff --git a/app/classes/minecraft/serverjars.py b/app/classes/minecraft/serverjars.py
index 380dbd38..01ad1fb1 100644
--- a/app/classes/minecraft/serverjars.py
+++ b/app/classes/minecraft/serverjars.py
@@ -137,7 +137,8 @@ class ServerJars:
# jar versions for this server
versions = self._get_jar_details(s)
- # add these versions (a list) to the dict with a key of the server type
+ # add these versions (a list) to the dict with
+ # a key of the server type
data["servers"].update({s: versions})
# save our cache
@@ -177,7 +178,8 @@ class ServerJars:
fetch_url = f"{self.base_url}/api/fetchJar/{server}/{version}"
server_users = server_permissions.get_server_user_list(server_id)
- # We need to make sure the server is registered before we submit a db update for it's stats.
+ # We need to make sure the server is registered before
+ # we submit a db update for it's stats.
while True:
try:
Servers_Controller.set_download(server_id)
diff --git a/app/classes/minecraft/stats.py b/app/classes/minecraft/stats.py
index 3fcc780e..b4db5515 100644
--- a/app/classes/minecraft/stats.py
+++ b/app/classes/minecraft/stats.py
@@ -67,7 +67,7 @@ class Stats:
except Exception as e:
logger.error(
- f"Unable to get process details for pid: {process_pid} due to error: {e}"
+ f"Unable to get process details for pid: {process_pid} Error: {e}"
)
# Dummy Data
@@ -77,7 +77,7 @@ class Stats:
}
return process_stats
- # shamelessly stolen from https://github.com/giampaolo/psutil/blob/master/scripts/disk_usage.py
+ # Source: https://github.com/giampaolo/psutil/blob/master/scripts/disk_usage.py
@staticmethod
def _all_disk_usage():
disk_data = []
@@ -207,26 +207,29 @@ class Stats:
}
).execute()
- # server_stats = stats_to_send.get('servers')#
- #
- # for server in server_stats:
- # Server_Stats.insert({
- # Server_Stats.server_id: server.get('id', 0),
- # Server_Stats.started: server.get('started', ""),
- # Server_Stats.running: server.get('running', False),
- # Server_Stats.cpu: server.get('cpu', 0),
- # Server_Stats.mem: server.get('mem', 0),
- # Server_Stats.mem_percent: server.get('mem_percent', 0),
- # Server_Stats.world_name: server.get('world_name', ""),
- # Server_Stats.world_size: server.get('world_size', ""),
- # Server_Stats.server_port: server.get('server_port', ""),
- # Server_Stats.int_ping_results: server.get('int_ping_results', False),
- # Server_Stats.online: server.get("online", False),
- # Server_Stats.max: server.get("max", False),
- # Server_Stats.players: server.get("players", False),
- # Server_Stats.desc: server.get("desc", False),
- # Server_Stats.version: server.get("version", False)
- # }).execute()
+ # server_stats = stats_to_send.get("servers")
+ # for server in server_stats:
+ # Server_Stats.insert(
+ # {
+ # Server_Stats.server_id: server.get("id", 0),
+ # Server_Stats.started: server.get("started", ""),
+ # Server_Stats.running: server.get("running", False),
+ # Server_Stats.cpu: server.get("cpu", 0),
+ # Server_Stats.mem: server.get("mem", 0),
+ # Server_Stats.mem_percent: server.get("mem_percent", 0),
+ # Server_Stats.world_name: server.get("world_name", ""),
+ # Server_Stats.world_size: server.get("world_size", ""),
+ # Server_Stats.server_port: server.get("server_port", ""),
+ # Server_Stats.int_ping_results: server.get(
+ # "int_ping_results", False
+ # ),
+ # Server_Stats.online: server.get("online", False),
+ # Server_Stats.max: server.get("max", False),
+ # Server_Stats.players: server.get("players", False),
+ # Server_Stats.desc: server.get("desc", False),
+ # Server_Stats.version: server.get("version", False),
+ # }
+ # ).execute()
# delete old data
max_age = helper.get_setting("history_max_age")
diff --git a/app/classes/models/crafty_permissions.py b/app/classes/models/crafty_permissions.py
index 46b02315..fbe8ab0e 100644
--- a/app/classes/models/crafty_permissions.py
+++ b/app/classes/models/crafty_permissions.py
@@ -26,9 +26,9 @@ database = SqliteDatabase(
)
-# ************************************************************************************************
+# **********************************************************************************
# User_Crafty Class
-# ************************************************************************************************
+# **********************************************************************************
class User_Crafty(Model):
user_id = ForeignKeyField(Users, backref="users_crafty")
permissions = CharField(default="00000000")
@@ -44,9 +44,9 @@ class User_Crafty(Model):
database = database
-# ************************************************************************************************
+# **********************************************************************************
# Crafty Permissions Class
-# ************************************************************************************************
+# **********************************************************************************
class Enum_Permissions_Crafty(Enum):
Server_Creation = 0
User_Config = 1
@@ -54,10 +54,9 @@ class Enum_Permissions_Crafty(Enum):
class Permissions_Crafty:
-
- # ************************************************************************************************
+ # **********************************************************************************
# Crafty Permissions Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_permissions_list():
permissions_list = []
@@ -113,15 +112,15 @@ class Permissions_Crafty:
def get_permission_quantity_list(user_id):
user_crafty = crafty_permissions.get_User_Crafty(user_id)
quantity_list = {
- Enum_Permissions_Crafty.Server_Creation.name: user_crafty.limit_server_creation,
+ Enum_Permissions_Crafty.Server_Creation.name: user_crafty.limit_server_creation, # pylint: disable=line-too-long
Enum_Permissions_Crafty.User_Config.name: user_crafty.limit_user_creation,
Enum_Permissions_Crafty.Roles_Config.name: user_crafty.limit_role_creation,
}
return quantity_list
- # ************************************************************************************************
+ # **********************************************************************************
# User_Crafty Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_User_Crafty(user_id):
try:
diff --git a/app/classes/models/management.py b/app/classes/models/management.py
index 2e55bd49..039ceeeb 100644
--- a/app/classes/models/management.py
+++ b/app/classes/models/management.py
@@ -33,9 +33,9 @@ database = SqliteDatabase(
helper.db_path, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
)
-# ************************************************************************************************
+# **********************************************************************************
# Audit_Log Class
-# ************************************************************************************************
+# **********************************************************************************
class Audit_Log(Model):
audit_id = AutoField()
created = DateTimeField(default=datetime.datetime.now)
@@ -51,9 +51,9 @@ class Audit_Log(Model):
database = database
-# ************************************************************************************************
+# **********************************************************************************
# Host_Stats Class
-# ************************************************************************************************
+# **********************************************************************************
class Host_Stats(Model):
time = DateTimeField(default=datetime.datetime.now, index=True)
boot_time = CharField(default="")
@@ -71,9 +71,9 @@ class Host_Stats(Model):
database = database
-# ************************************************************************************************
+# **********************************************************************************
# Commands Class
-# ************************************************************************************************
+# **********************************************************************************
class Commands(Model):
command_id = AutoField()
created = DateTimeField(default=datetime.datetime.now)
@@ -88,9 +88,9 @@ class Commands(Model):
database = database
-# ************************************************************************************************
+# **********************************************************************************
# Webhooks Class
-# ************************************************************************************************
+# **********************************************************************************
class Webhooks(Model):
id = AutoField()
name = CharField(max_length=64, unique=True, index=True)
@@ -104,9 +104,9 @@ class Webhooks(Model):
database = database
-# ************************************************************************************************
+# **********************************************************************************
# Schedules Class
-# ************************************************************************************************
+# **********************************************************************************
class Schedules(Model):
schedule_id = IntegerField(unique=True, primary_key=True)
server_id = ForeignKeyField(Servers, backref="schedule_server")
@@ -127,9 +127,9 @@ class Schedules(Model):
database = database
-# ************************************************************************************************
+# **********************************************************************************
# Backups Class
-# ************************************************************************************************
+# **********************************************************************************
class Backups(Model):
excluded_dirs = CharField(null=True)
max_backups = IntegerField()
@@ -143,18 +143,18 @@ class Backups(Model):
class helpers_management:
- # ************************************************************************************************
+ # **********************************************************************************
# Host_Stats Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_latest_hosts_stats():
# pylint: disable=no-member
query = Host_Stats.select().order_by(Host_Stats.id.desc()).get()
return model_to_dict(query)
- # ************************************************************************************************
+ # **********************************************************************************
# Commands Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def add_command(server_id, user_id, remote_ip, command):
Commands.insert(
@@ -179,9 +179,9 @@ class helpers_management:
Commands.command_id == command_id
).execute()
- # ************************************************************************************************
+ # **********************************************************************************
# Audit_Log Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_actity_log():
q = Audit_Log.select()
@@ -243,9 +243,9 @@ class helpers_management:
else:
return
- # ************************************************************************************************
+ # **********************************************************************************
# Schedules Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def create_scheduled_task(
server_id,
@@ -325,9 +325,9 @@ class helpers_management:
# pylint: disable=singleton-comparison
return Schedules.select().where(Schedules.enabled == True).execute()
- # ************************************************************************************************
+ # **********************************************************************************
# Backups Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_backup_config(server_id):
try:
diff --git a/app/classes/models/roles.py b/app/classes/models/roles.py
index 6724aafb..ff705e96 100644
--- a/app/classes/models/roles.py
+++ b/app/classes/models/roles.py
@@ -24,9 +24,9 @@ database = SqliteDatabase(
helper.db_path, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
)
-# ************************************************************************************************
+# **********************************************************************************
# Roles Class
-# ************************************************************************************************
+# **********************************************************************************
class Roles(Model):
role_id = AutoField()
created = DateTimeField(default=datetime.datetime.now)
@@ -38,9 +38,9 @@ class Roles(Model):
database = database
-# ************************************************************************************************
+# **********************************************************************************
# Roles Helpers
-# ************************************************************************************************
+# **********************************************************************************
class helper_roles:
@staticmethod
def get_all_roles():
diff --git a/app/classes/models/server_permissions.py b/app/classes/models/server_permissions.py
index a4024873..92ecbd09 100644
--- a/app/classes/models/server_permissions.py
+++ b/app/classes/models/server_permissions.py
@@ -27,9 +27,9 @@ database = SqliteDatabase(
helper.db_path, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
)
-# ************************************************************************************************
+# **********************************************************************************
# Role Servers Class
-# ************************************************************************************************
+# **********************************************************************************
class Role_Servers(Model):
role_id = ForeignKeyField(Roles, backref="role_server")
server_id = ForeignKeyField(Servers, backref="role_server")
@@ -41,9 +41,9 @@ class Role_Servers(Model):
database = database
-# ************************************************************************************************
+# **********************************************************************************
# Servers Permissions Class
-# ************************************************************************************************
+# **********************************************************************************
class Enum_Permissions_Server(Enum):
Commands = 0
Terminal = 1
@@ -104,9 +104,9 @@ class Permissions_Servers:
permissions_list.append(member[1])
return permissions_list
- # ************************************************************************************************
+ # **********************************************************************************
# Role_Servers Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_role_servers_from_role_id(roleid):
return Role_Servers.select().where(Role_Servers.role_id == roleid)
diff --git a/app/classes/models/servers.py b/app/classes/models/servers.py
index 8d5526ec..f9c777a1 100644
--- a/app/classes/models/servers.py
+++ b/app/classes/models/servers.py
@@ -27,9 +27,9 @@ database = SqliteDatabase(
helper.db_path, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
)
-# ************************************************************************************************
+# **********************************************************************************
# Servers Class
-# ************************************************************************************************
+# **********************************************************************************
class Servers(Model):
server_id = AutoField()
created = DateTimeField(default=datetime.datetime.now)
@@ -55,9 +55,9 @@ class Servers(Model):
database = database
-# ************************************************************************************************
+# **********************************************************************************
# Servers Stats Class
-# ************************************************************************************************
+# **********************************************************************************
class Server_Stats(Model):
stats_id = AutoField()
created = DateTimeField(default=datetime.datetime.now)
@@ -87,14 +87,14 @@ class Server_Stats(Model):
database = database
-# ************************************************************************************************
+# **********************************************************************************
# Servers Class
-# ************************************************************************************************
+# **********************************************************************************
class helper_servers:
- # ************************************************************************************************
+ # **********************************************************************************
# Generic Servers Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def create_server(
name: str,
@@ -152,9 +152,9 @@ class helper_servers:
except IndexError:
return {}
- # ************************************************************************************************
+ # **********************************************************************************
# Servers Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_all_defined_servers():
query = Servers.select()
@@ -188,12 +188,15 @@ class helper_servers:
@staticmethod
def get_server_friendly_name(server_id):
server_data = servers_helper.get_server_data_by_id(server_id)
- friendly_name = f"{server_data.get('server_name', None)} with ID: {server_data.get('server_id', 0)}"
+ friendly_name = (
+ f"{server_data.get('server_name', None)} "
+ f"with ID: {server_data.get('server_id', 0)}"
+ )
return friendly_name
- # ************************************************************************************************
+ # **********************************************************************************
# Servers_Stats Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_latest_server_stats(server_id):
return (
diff --git a/app/classes/models/users.py b/app/classes/models/users.py
index 24020e61..a78862ba 100644
--- a/app/classes/models/users.py
+++ b/app/classes/models/users.py
@@ -30,9 +30,9 @@ database = SqliteDatabase(
helper.db_path, pragmas={"journal_mode": "wal", "cache_size": -1024 * 10}
)
-# ************************************************************************************************
+# **********************************************************************************
# Users Class
-# ************************************************************************************************
+# **********************************************************************************
class Users(Model):
user_id = AutoField()
created = DateTimeField(default=datetime.datetime.now)
@@ -55,9 +55,9 @@ class Users(Model):
database = database
-# ************************************************************************************************
+# **********************************************************************************
# API Keys Class
-# ************************************************************************************************
+# **********************************************************************************
class ApiKeys(Model):
token_id = AutoField()
name = CharField(default="", unique=True, index=True)
@@ -72,9 +72,9 @@ class ApiKeys(Model):
database = database
-# ************************************************************************************************
+# **********************************************************************************
# User Roles Class
-# ************************************************************************************************
+# **********************************************************************************
class User_Roles(Model):
user_id = ForeignKeyField(Users, backref="user_role")
role_id = ForeignKeyField(Roles, backref="user_role")
@@ -85,9 +85,9 @@ class User_Roles(Model):
database = database
-# ************************************************************************************************
+# **********************************************************************************
# Users Helpers
-# ************************************************************************************************
+# **********************************************************************************
class helper_users:
@staticmethod
def get_by_id(user_id):
@@ -260,9 +260,9 @@ class helper_users:
return False
return True
- # ************************************************************************************************
+ # **********************************************************************************
# User_Roles Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_or_create(user_id, role_id):
@@ -335,9 +335,9 @@ class helper_users:
def remove_roles_from_role_id(role_id):
User_Roles.delete().where(User_Roles.role_id == role_id).execute()
- # ************************************************************************************************
+ # **********************************************************************************
# ApiKeys Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def get_user_api_keys(user_id: str):
diff --git a/app/classes/shared/authentication.py b/app/classes/shared/authentication.py
index 6592fdd3..6f4d5bcc 100644
--- a/app/classes/shared/authentication.py
+++ b/app/classes/shared/authentication.py
@@ -63,7 +63,8 @@ class Authentication:
return None
user_id: str = data["user_id"]
user = users_helper.get_user(user_id)
- # TODO: Have a cache or something so we don't constantly have to query the database
+ # TODO: Have a cache or something so we don't constantly
+ # have to query the database
if int(user.get("valid_tokens_from").timestamp()) < iat:
# Success!
return key, data, user
diff --git a/app/classes/shared/command.py b/app/classes/shared/command.py
index 8907f4c5..0df70648 100644
--- a/app/classes/shared/command.py
+++ b/app/classes/shared/command.py
@@ -56,7 +56,8 @@ class MainPrompt(cmd.Cmd):
for thread in threading.enumerate():
if sys.version_info >= (3, 8):
print(
- f"Name: {thread.name} Identifier: {thread.ident} TID/PID: {thread.native_id}"
+ f"Name: {thread.name} Identifier: "
+ f"{thread.ident} TID/PID: {thread.native_id}"
)
else:
print(f"Name: {thread.name} Identifier: {thread.ident}")
diff --git a/app/classes/shared/file_helpers.py b/app/classes/shared/file_helpers.py
index a706d115..bc21da51 100644
--- a/app/classes/shared/file_helpers.py
+++ b/app/classes/shared/file_helpers.py
@@ -76,7 +76,8 @@ class FileHelpers:
except Exception as e:
logger.warning(
- f"Error backing up: {os.path.join(root, file)}! - Error was: {e}"
+ f"Error backing up: {os.path.join(root, file)}!"
+ f" - Error was: {e}"
)
return True
@@ -104,7 +105,8 @@ class FileHelpers:
except Exception as e:
logger.warning(
- f"Error backing up: {os.path.join(root, file)}! - Error was: {e}"
+ f"Error backing up: {os.path.join(root, file)}!"
+ f" - Error was: {e}"
)
return True
diff --git a/app/classes/shared/helpers.py b/app/classes/shared/helpers.py
index cbc75b2a..6deb85ee 100644
--- a/app/classes/shared/helpers.py
+++ b/app/classes/shared/helpers.py
@@ -142,28 +142,26 @@ class Helpers:
ci = -1 # command index - pointer to the argument we're building in cmd_out
np = True # whether we're creating a new argument/parameter
esc = False # whether an escape character was encountered
- stch = None # if we're dealing with a quote, save the quote type here. Nested quotes to be dealt with by the command
+ stch = None # if we're dealing with a quote, save the quote type here.
+ # Nested quotes to be dealt with by the command
for c in cmd_in: # for character in string
- if (
- np
- ): # if set, begin a new argument and increment the command index. Continue the loop.
+ if np: # if set, begin a new argument and increment the command index.
+ # Continue the loop.
if c == " ":
continue
else:
ci += 1
cmd_out.append("")
np = False
- if (
- esc
- ): # if we encountered an escape character on the last loop, append this char regardless of what it is
+ if esc: # if we encountered an escape character on the last loop,
+ # append this char regardless of what it is
if c not in Helpers.allowed_quotes:
cmd_out[ci] += "\\"
cmd_out[ci] += c
esc = False
else:
- if (
- c == "\\"
- ): # if the current character is an escape character, set the esc flag and continue to next loop
+ if c == "\\": # if the current character is an escape character,
+ # set the esc flag and continue to next loop
esc = True
elif (
c == " " and stch is None
@@ -172,12 +170,13 @@ class Helpers:
np = True
elif (
c == stch
- ): # if we encounter the character that matches our start quote, end the quote and continue to next loop
+ ): # if we encounter the character that matches our start quote,
+ # end the quote and continue to next loop
stch = None
elif stch is None and (
c in Helpers.allowed_quotes
- ): # 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
+ ): # if we're not in the middle of a quote and we get a quotable
+ # character, start a quote and proceed to the next loop
stch = c
else: # else, just store the character in the current arg
cmd_out[ci] += c
@@ -236,8 +235,9 @@ class Helpers:
def get_announcements():
r = requests.get("https://craftycontrol.com/notify.json", timeout=2)
data = (
- '[{"id":"1","date":"Unknown","title":"Error getting Announcements","desc":"Error getting '
- 'Announcements","link":""}] '
+ '[{"id":"1","date":"Unknown",'
+ '"title":"Error getting Announcements",'
+ '"desc":"Error getting Announcements","link":""}]'
)
if r.status_code in [200, 201]:
@@ -337,7 +337,8 @@ class Helpers:
# get file size
fsize = f.tell()
- # set pos @ last n chars (buffer from above = number of lines * avg_line_length)
+ # set pos @ last n chars
+ # (buffer from above = number of lines * avg_line_length)
f.seek(max(fsize - line_buffer, 0), 0)
# read file til the end
@@ -455,7 +456,8 @@ class Helpers:
@staticmethod
def calc_percent(source_path, dest_path):
- # calculates percentable of zip from drive. Not with compression. For backups and support logs
+ # calculates percentable of zip from drive. Not with compression.
+ # (For backups and support logs)
source_size = 0
files_count = 0
for path, _dirs, files in os.walk(source_path):
@@ -539,13 +541,15 @@ class Helpers:
started = data.get("started")
if psutil.pid_exists(pid):
console.critical(
- f"Another Crafty Controller agent seems to be running...\npid: {pid} \nstarted on: {started}"
+ f"Another Crafty Controller agent seems to be running..."
+ f"\npid: {pid} \nstarted on: {started}"
)
logger.critical("Found running crafty process. Exiting.")
sys.exit(1)
else:
logger.info(
- "No process found for pid. Assuming crafty crashed. Deleting stale session.lock"
+ "No process found for pid. Assuming "
+ "crafty crashed. Deleting stale session.lock"
)
os.remove(self.session_file)
@@ -564,7 +568,8 @@ class Helpers:
with open(self.session_file, "w", encoding="utf-8") as f:
json.dump(session_data, f, indent=True)
- # because this is a recursive function, we will return bytes, and set human readable later
+ # because this is a recursive function, we will return bytes,
+ # and set human readable later
def get_dir_size(self, path: str):
total = 0
for entry in os.scandir(path):
@@ -610,7 +615,8 @@ class Helpers:
"""
ensures a directory exists
- Checks for the existence of a directory, if the directory isn't there, this function creates the directory
+ Checks for the existence of a directory, if the directory isn't there,
+ this function creates the directory
Args:
path (string): the path you are checking for
@@ -769,7 +775,8 @@ class Helpers:
class="tree-nested d-block tree-ctx-item tree-file tree-item"
data-path="{dpath}"
data-name="{filename}"
- onclick="clickOnFile(event)">{filename}"""
+ onclick="clickOnFile(event)">
+ {filename}"""
return output
@staticmethod
@@ -805,7 +812,8 @@ class Helpers:
class="tree-nested d-block tree-ctx-item tree-file tree-item"
data-path="{dpath}"
data-name="{filename}"
- onclick="clickOnFile(event)">{filename}"""
+ onclick="clickOnFile(event)">
+ {filename}"""
output += "\n"
return output
@@ -883,13 +891,16 @@ class Helpers:
@staticmethod
def in_path(parent_path, child_path):
- # Smooth out relative path names, note: if you are concerned about symbolic links, you should use os.path.realpath too
+ # Smooth out relative path names, note: if you are concerned about
+ # symbolic links, you should use os.path.realpath too
parent_path = os.path.abspath(parent_path)
child_path = os.path.abspath(child_path)
- # Compare the common path of the parent and child path with the common path of just the parent path.
- # Using the commonpath method on just the parent path will regularise the path name in the same way
- # as the comparison that deals with both paths, removing any trailing path separator
+ # Compare the common path of the parent and child path with the
+ # common path of just the parent path. Using the commonpath method
+ # on just the parent path will regularise the path name in the same way
+ # as the comparison that deals with both paths, removing any trailing
+ # path separator
return os.path.commonpath([parent_path]) == os.path.commonpath(
[parent_path, child_path]
)
diff --git a/app/classes/shared/import3.py b/app/classes/shared/import3.py
index 024dd444..404639d4 100644
--- a/app/classes/shared/import3.py
+++ b/app/classes/shared/import3.py
@@ -1,87 +1,95 @@
-import json
-import os
-import logging
-
-from app.classes.controllers.users_controller import users_helper
-from app.classes.shared.main_controller import Controller
-from app.classes.shared.console import console
-
-logger = logging.getLogger(__name__)
-
-
-class import3:
- def __init__(self):
- self.controller = Controller()
-
- def start_import(self):
- folder = os.path.normpath(
- input(
- "Please input the path to the migrations folder in your installation of Crafty 3: "
- )
- )
- if not os.path.exists(folder):
- console.info(
- "Crafty cannot find the path you entered. Does Crafty's user have permission to access it?"
- )
- console.info("Please run the import3 command again and enter a valid path.")
- else:
- with open(os.path.join(folder, "users.json"), encoding="utf-8") as f:
- user_json = json.loads(f.read())
- with open(os.path.join(folder, "mc_settings.json"), encoding="utf-8") as f:
- servers_json = json.loads(f.read())
- self.import_users(user_json)
- self.import_servers(servers_json, self.controller)
-
- @staticmethod
- def import_users(json_data):
- # If there is only one user to import json needs to call the data differently
- if isinstance(json_data, list):
- for user in json_data:
- users_helper.add_rawpass_user(user["username"], user["password"])
- console.info(f"Imported user {user['username']} from Crafty 3")
- logger.info(f"Imported user {user['username']} from Crafty 3")
- else:
- console.info(
- "There is only one user detected. Cannot create duplicate Admin account."
- )
- logger.info(
- "There is only one user detected. Cannot create duplicate Admin account."
- )
-
- @staticmethod
- def import_servers(json_data, controller):
- # If there is only one server to import json needs to call the data differently
- if isinstance(json_data, list):
- for server in json_data:
- new_server_id = controller.import_jar_server(
- server_name=server["server_name"],
- server_path=server["server_path"],
- server_jar=server["server_jar"],
- min_mem=(int(server["memory_min"]) / 1000),
- max_mem=(int(server["memory_max"]) / 1000),
- port=server["server_port"],
- )
- console.info(
- f"Imported server {server['server_name']}[{server['id']}] from Crafty 3 to new server id {new_server_id}"
- )
- logger.info(
- f"Imported server {server['server_name']}[{server['id']}] from Crafty 3 to new server id {new_server_id}"
- )
- else:
- new_server_id = controller.import_jar_server(
- server_name=json_data["server_name"],
- server_path=json_data["server_path"],
- server_jar=json_data["server_jar"],
- min_mem=(int(json_data["memory_min"]) / 1000),
- max_mem=(int(json_data["memory_max"]) / 1000),
- port=json_data["server_port"],
- )
- console.info(
- f"Imported server {json_data['server_name']}[{json_data['id']}] from Crafty 3 to new server id {new_server_id}"
- )
- logger.info(
- f"Imported server {json_data['server_name']}[{json_data['id']}] from Crafty 3 to new server id {new_server_id}"
- )
-
-
-import3 = import3()
+import json
+import os
+import logging
+
+from app.classes.controllers.users_controller import users_helper
+from app.classes.shared.main_controller import Controller
+from app.classes.shared.console import console
+
+logger = logging.getLogger(__name__)
+
+
+class import3:
+ def __init__(self):
+ self.controller = Controller()
+
+ def start_import(self):
+ folder = os.path.normpath(
+ input(
+ "Please input the path to the migrations folder "
+ "in your installation of Crafty 3: "
+ )
+ )
+ if not os.path.exists(folder):
+ console.info(
+ "Crafty cannot find the path you entered. "
+ "Does Crafty's user have permission to access it?"
+ )
+ console.info("Please run the import3 command again and enter a valid path.")
+ else:
+ with open(os.path.join(folder, "users.json"), encoding="utf-8") as f:
+ user_json = json.loads(f.read())
+ with open(os.path.join(folder, "mc_settings.json"), encoding="utf-8") as f:
+ servers_json = json.loads(f.read())
+ self.import_users(user_json)
+ self.import_servers(servers_json, self.controller)
+
+ @staticmethod
+ def import_users(json_data):
+ # If there is only one user to import json needs to call the data differently
+ if isinstance(json_data, list):
+ for user in json_data:
+ users_helper.add_rawpass_user(user["username"], user["password"])
+ console.info(f"Imported user {user['username']} from Crafty 3")
+ logger.info(f"Imported user {user['username']} from Crafty 3")
+ else:
+ console.info(
+ "There is only one user detected. "
+ "Cannot create duplicate Admin account."
+ )
+ logger.info(
+ "There is only one user detected. "
+ "Cannot create duplicate Admin account."
+ )
+
+ @staticmethod
+ def import_servers(json_data, controller):
+ # If there is only one server to import json needs to call the data differently
+ if isinstance(json_data, list):
+ for server in json_data:
+ new_server_id = controller.import_jar_server(
+ server_name=server["server_name"],
+ server_path=server["server_path"],
+ server_jar=server["server_jar"],
+ min_mem=(int(server["memory_min"]) / 1000),
+ max_mem=(int(server["memory_max"]) / 1000),
+ port=server["server_port"],
+ )
+ console.info(
+ f"Imported server {server['server_name']}[{server['id']}] "
+ f"from Crafty 3 to new server id {new_server_id}"
+ )
+ logger.info(
+ f"Imported server {server['server_name']}[{server['id']}] "
+ f"from Crafty 3 to new server id {new_server_id}"
+ )
+ else:
+ new_server_id = controller.import_jar_server(
+ server_name=json_data["server_name"],
+ server_path=json_data["server_path"],
+ server_jar=json_data["server_jar"],
+ min_mem=(int(json_data["memory_min"]) / 1000),
+ max_mem=(int(json_data["memory_max"]) / 1000),
+ port=json_data["server_port"],
+ )
+ console.info(
+ f"Imported server {json_data['server_name']}[{json_data['id']}] "
+ f"from Crafty 3 to new server id {new_server_id}"
+ )
+ logger.info(
+ f"Imported server {json_data['server_name']}[{json_data['id']}] "
+ f"from Crafty 3 to new server id {new_server_id}"
+ )
+
+
+import3 = import3()
diff --git a/app/classes/shared/main_controller.py b/app/classes/shared/main_controller.py
index eefefb7e..71a5f741 100644
--- a/app/classes/shared/main_controller.py
+++ b/app/classes/shared/main_controller.py
@@ -64,7 +64,8 @@ class Controller:
if known_server == server_id_to_check:
logger.info(
- f"skipping initialization of server {server_id_to_check} because it is already loaded"
+ f"skipping initialization of server {server_id_to_check} "
+ f"because it is already loaded"
)
return True
@@ -86,11 +87,13 @@ class Controller:
helper.get_os_understandable_path(s["path"])
):
logger.warning(
- f"Unable to find server {s['server_name']} at path {s['path']}. Skipping this server"
+ f"Unable to find server {s['server_name']} at path {s['path']}. "
+ f"Skipping this server"
)
console.warning(
- f"Unable to find server {s['server_name']} at path {s['path']}. Skipping this server"
+ f"Unable to find server {s['server_name']} at path {s['path']}. "
+ f"Skipping this server"
)
continue
@@ -180,7 +183,8 @@ class Controller:
auth_servers.append(server)
else:
logger.info(
- f"Logs permission not available for server {server['server_name']}. Skipping."
+ f"Logs permission not available for server "
+ f"{server['server_name']}. Skipping."
)
# we'll iterate through our list of log paths from auth servers.
for server in auth_servers:
@@ -242,7 +246,8 @@ class Controller:
def crash_detection(self, server_obj):
svr = self.get_server_obj(server_obj.server_id)
# start or stop crash detection depending upon user preference
- # The below functions check to see if the server is running. They only execute if it's running.
+ # The below functions check to see if the server is running.
+ # They only execute if it's running.
if server_obj.crash_detection == 1:
svr.start_crash_detection()
else:
@@ -366,11 +371,18 @@ class Controller:
logger.error(f"Unable to create required server files due to :{e}")
return False
- # must remain non-fstring due to string addtion
if helper.is_os_windows():
- server_command = f'java -Xms{helper.float_to_string(min_mem)}M -Xmx{helper.float_to_string(max_mem)}M -jar "{full_jar_path}" nogui'
+ server_command = (
+ f"java -Xms{helper.float_to_string(min_mem)}M "
+ f"-Xmx{helper.float_to_string(max_mem)}M "
+ f'-jar "{full_jar_path}" nogui'
+ )
else:
- server_command = f"java -Xms{helper.float_to_string(min_mem)}M -Xmx{helper.float_to_string(max_mem)}M -jar {full_jar_path} nogui"
+ server_command = (
+ f"java -Xms{helper.float_to_string(min_mem)}M "
+ f"-Xmx{helper.float_to_string(max_mem)}M "
+ f"-jar {full_jar_path} nogui"
+ )
server_log_file = f"{server_dir}/logs/latest.log"
server_stop = "stop"
@@ -441,7 +453,8 @@ class Controller:
has_properties = True
if not has_properties:
logger.info(
- f"No server.properties found on zip file import. Creating one with port selection of {str(port)}"
+ f"No server.properties found on zip file import. "
+ f"Creating one with port selection of {str(port)}"
)
with open(
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
@@ -451,11 +464,18 @@ class Controller:
full_jar_path = os.path.join(new_server_dir, server_jar)
- # due to adding strings this must not be an fstring
if helper.is_os_windows():
- server_command = f'java -Xms{helper.float_to_string(min_mem)}M -Xmx{helper.float_to_string(max_mem)}M -jar "{full_jar_path}" nogui'
+ server_command = (
+ f"java -Xms{helper.float_to_string(min_mem)}M "
+ f"-Xmx{helper.float_to_string(max_mem)}M "
+ f'-jar "{full_jar_path}" nogui'
+ )
else:
- server_command = f"java -Xms{helper.float_to_string(min_mem)}M -Xmx{helper.float_to_string(max_mem)}M -jar {full_jar_path} nogui"
+ server_command = (
+ f"java -Xms{helper.float_to_string(min_mem)}M "
+ f"-Xmx{helper.float_to_string(max_mem)}M "
+ f"-jar {full_jar_path} nogui"
+ )
server_log_file = f"{new_server_dir}/logs/latest.log"
server_stop = "stop"
@@ -512,7 +532,8 @@ class Controller:
logger.error(f"ERROR IN ZIP IMPORT: {ex}")
if not has_properties:
logger.info(
- f"No server.properties found on zip file import. Creating one with port selection of {str(port)}"
+ f"No server.properties found on zip file import. "
+ f"Creating one with port selection of {str(port)}"
)
with open(
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
@@ -522,11 +543,18 @@ class Controller:
full_jar_path = os.path.join(new_server_dir, server_jar)
- # due to strings being added we need to leave this as not an fstring
if helper.is_os_windows():
- server_command = f'java -Xms{helper.float_to_string(min_mem)}M -Xmx{helper.float_to_string(max_mem)}M -jar "{full_jar_path}" nogui'
+ server_command = (
+ f"java -Xms{helper.float_to_string(min_mem)}M "
+ f"-Xmx{helper.float_to_string(max_mem)}M "
+ f'-jar "{full_jar_path}" nogui'
+ )
else:
- server_command = f"java -Xms{helper.float_to_string(min_mem)}M -Xmx{helper.float_to_string(max_mem)}M -jar {full_jar_path} nogui"
+ server_command = (
+ f"java -Xms{helper.float_to_string(min_mem)}M "
+ f"-Xmx{helper.float_to_string(max_mem)}M "
+ f"-jar {full_jar_path} nogui"
+ )
logger.debug("command: " + server_command)
server_log_file = f"{new_server_dir}/logs/latest.log"
server_stop = "stop"
@@ -545,9 +573,9 @@ class Controller:
)
return new_id
- # ************************************************************************************************
+ # **********************************************************************************
# BEDROCK IMPORTS
- # ************************************************************************************************
+ # **********************************************************************************
def import_bedrock_server(
self, server_name: str, server_path: str, server_exe: str, port: int
@@ -575,7 +603,8 @@ class Controller:
has_properties = True
if not has_properties:
logger.info(
- f"No server.properties found on zip file import. Creating one with port selection of {str(port)}"
+ f"No server.properties found on zip file import. "
+ f"Creating one with port selection of {str(port)}"
)
with open(
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
@@ -585,7 +614,6 @@ class Controller:
full_jar_path = os.path.join(new_server_dir, server_exe)
- # due to adding strings this must not be an fstring
if helper.is_os_windows():
server_command = f'"{full_jar_path}"'
else:
@@ -644,7 +672,8 @@ class Controller:
logger.error(f"ERROR IN ZIP IMPORT: {ex}")
if not has_properties:
logger.info(
- f"No server.properties found on zip file import. Creating one with port selection of {str(port)}"
+ f"No server.properties found on zip file import. "
+ f"Creating one with port selection of {str(port)}"
)
with open(
os.path.join(new_server_dir, "server.properties"), "w", encoding="utf-8"
@@ -654,7 +683,6 @@ class Controller:
full_jar_path = os.path.join(new_server_dir, server_exe)
- # due to strings being added we need to leave this as not an fstring
if helper.is_os_windows():
server_command = f'"{full_jar_path}"'
else:
@@ -681,9 +709,9 @@ class Controller:
return new_id
- # ************************************************************************************************
+ # **********************************************************************************
# BEDROCK IMPORTS END
- # ************************************************************************************************
+ # **********************************************************************************
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)
@@ -743,7 +771,8 @@ class Controller:
encoding="utf-8",
) as f:
f.write(
- "The server is managed by Crafty Controller.\n Leave this directory/files alone please"
+ "The server is managed by Crafty Controller.\n "
+ "Leave this directory/files alone please"
)
f.close()
@@ -782,7 +811,8 @@ class Controller:
)
except Exception as e:
logger.error(
- f"Unable to delete server files for server with ID: {server_id} with error logged: {e}"
+ f"Unable to delete server files for server with ID: "
+ f"{server_id} with error logged: {e}"
)
if helper.check_path_exists(
self.servers.get_server_data_by_id(server_id)["backup_path"]
diff --git a/app/classes/shared/main_models.py b/app/classes/shared/main_models.py
index b1a79bb9..dcd4296f 100644
--- a/app/classes/shared/main_models.py
+++ b/app/classes/shared/main_models.py
@@ -53,9 +53,9 @@ class db_builder:
class db_shortcuts:
- # ************************************************************************************************
+ # **********************************************************************************
# Generic Databse Methods
- # ************************************************************************************************
+ # **********************************************************************************
@staticmethod
def return_rows(query):
rows = []
@@ -75,8 +75,8 @@ class db_shortcuts:
return data
-# ************************************************************************************************
+# **********************************************************************************
# Static Accessors
-# ************************************************************************************************
+# **********************************************************************************
installer = db_builder()
db_helper = db_shortcuts()
diff --git a/app/classes/shared/server.py b/app/classes/shared/server.py
index 5c7541e2..7f846b6e 100644
--- a/app/classes/shared/server.py
+++ b/app/classes/shared/server.py
@@ -67,7 +67,8 @@ class ServerOutBuf:
while True:
if self.proc.poll() is None:
char = self.proc.stdout.read(1).decode("utf-8", "ignore")
- # TODO: we may want to benchmark reading in blocks and userspace processing it later, reads are kind of expensive as a syscall
+ # TODO: we may want to benchmark reading in blocks and userspace
+ # processing it later, reads are kind of expensive as a syscall
self.process_byte(char)
else:
flush = self.proc.stdout.read().decode("utf-8", "ignore")
@@ -82,7 +83,8 @@ class ServerOutBuf:
logger.debug("Broadcasting new virtual terminal line")
- # TODO: Do not send data to clients who do not have permission to view this server's console
+ # TODO: Do not send data to clients who do not have permission to view
+ # this server's console
websocket_helper.broadcast_page_params(
"/panel/server_detail",
{"id": self.server_id},
@@ -91,9 +93,9 @@ class ServerOutBuf:
)
-# ************************************************************************************************
+# **********************************************************************************
# Minecraft Server Class
-# ************************************************************************************************
+# **********************************************************************************
class Server:
def __init__(self, stats):
# holders for our process
@@ -122,9 +124,9 @@ class Server:
servers_helper.server_crash_reset(self.server_id)
servers_helper.set_update(self.server_id, False)
- # ************************************************************************************************
+ # **********************************************************************************
# Minecraft Server Management
- # ************************************************************************************************
+ # **********************************************************************************
def reload_server_settings(self):
server_data = servers_helper.get_server_data_by_id(self.server_id)
self.settings = server_data
@@ -135,7 +137,9 @@ class Server:
autoStart = server_data_obj["auto_start"]
logger.info(
- f"Creating Server object: {serverId} | Server Name: {serverName} | Auto Start: {autoStart}"
+ f"Creating Server object: {serverId} | "
+ f"Server Name: {serverName} | "
+ f"Auto Start: {autoStart}"
)
self.server_id = serverId
self.name = serverName
@@ -259,7 +263,7 @@ class Server:
console.info(f"Launching Server {self.name} with command {self.server_command}")
# Checks for eula. Creates one if none detected.
- # If EULA is detected and not set to one of these true vaiants we offer to set it true.
+ # If EULA is detected and not set to true we offer to set it true.
if helper.check_file_exists(os.path.join(self.settings["path"], "eula.txt")):
f = open(
os.path.join(self.settings["path"], "eula.txt"), "r", encoding="utf-8"
@@ -289,7 +293,8 @@ class Server:
)
else:
logger.error(
- "Autostart failed due to EULA being false. Agree not sent due to auto start."
+ "Autostart failed due to EULA being false. "
+ "Agree not sent due to auto start."
)
return False
return False
@@ -334,7 +339,8 @@ class Server:
== "minecraft-bedrock"
):
logger.info(
- f"Bedrock and Unix detected for server {self.name}. Switching to appropriate execution string"
+ f"Bedrock and Unix detected for server {self.name}. "
+ f"Switching to appropriate execution string"
)
my_env = os.environ
my_env["LD_LIBRARY_PATH"] = self.server_path
@@ -456,18 +462,22 @@ class Server:
websocket_helper.broadcast_user(user, "send_start_reload", {})
else:
logger.warning(
- f"Server PID {self.process.pid} died right after starting - is this a server config issue?"
+ f"Server PID {self.process.pid} died right after starting "
+ f"- is this a server config issue?"
)
console.warning(
- f"Server PID {self.process.pid} died right after starting - is this a server config issue?"
+ f"Server PID {self.process.pid} died right after starting "
+ f"- is this a server config issue?"
)
if self.settings["crash_detection"]:
logger.info(
- f"Server {self.name} has crash detection enabled - starting watcher task"
+ f"Server {self.name} has crash detection enabled "
+ f"- starting watcher task"
)
console.info(
- f"Server {self.name} has crash detection enabled - starting watcher task"
+ f"Server {self.name} has crash detection enabled "
+ f"- starting watcher task"
)
self.server_scheduler.add_job(
@@ -484,24 +494,29 @@ class Server:
)
def stop_crash_detection(self):
- # This is only used if the crash detection settings change while the server is running.
+ # This is only used if the crash detection settings change
+ # while the server is running.
if self.check_running():
logger.info(f"Detected crash detection shut off for server {self.name}")
try:
self.server_scheduler.remove_job("c_" + str(self.server_id))
except:
logger.error(
- f"Removing crash watcher for server {self.name} failed. Assuming it was never started."
+ f"Removing crash watcher for server {self.name} failed. "
+ f"Assuming it was never started."
)
def start_crash_detection(self):
- # This is only used if the crash detection settings change while the server is running.
+ # This is only used if the crash detection settings change
+ # while the server is running.
if self.check_running():
logger.info(
- f"Server {self.name} has crash detection enabled - starting watcher task"
+ f"Server {self.name} has crash detection enabled "
+ f"- starting watcher task"
)
console.info(
- f"Server {self.name} has crash detection enabled - starting watcher task"
+ f"Server {self.name} has crash detection enabled "
+ "- starting watcher task"
)
self.server_scheduler.add_job(
self.detect_crash, "interval", seconds=30, id=f"c_{self.server_id}"
@@ -523,7 +538,8 @@ class Server:
self.server_scheduler.remove_job("c_" + str(self.server_id))
except:
logger.error(
- f"Removing crash watcher for server {self.name} failed. Assuming it was never started."
+ f"Removing crash watcher for server {self.name} failed. "
+ f"Assuming it was never started."
)
else:
# windows will need to be handled separately for Ctrl+C
@@ -541,7 +557,11 @@ class Server:
while running:
x = x + 1
- logstr = f"Server {server_name} is still running - waiting 2s to see if it stops ({int(60-(x*2))} seconds until force close)"
+ logstr = (
+ f"Server {server_name} is still running "
+ f"- waiting 2s to see if it stops ({int(60-(x*2))} "
+ f"seconds until force close)"
+ )
logger.info(logstr)
console.info(logstr)
running = self.check_running()
@@ -624,19 +644,23 @@ class Server:
if self.settings["crash_detection"]:
logger.warning(
- f"The server {name} has crashed and will be restarted. Restarting server"
+ f"The server {name} has crashed and will be restarted. "
+ f"Restarting server"
)
console.warning(
- f"The server {name} has crashed and will be restarted. Restarting server"
+ f"The server {name} has crashed and will be restarted. "
+ f"Restarting server"
)
self.run_threaded_server(None)
return True
else:
logger.critical(
- f"The server {name} has crashed, crash detection is disabled and it will not be restarted"
+ f"The server {name} has crashed, "
+ f"crash detection is disabled and it will not be restarted"
)
console.critical(
- f"The server {name} has crashed, crash detection is disabled and it will not be restarted"
+ f"The server {name} has crashed, "
+ f"crash detection is disabled and it will not be restarted"
)
return False
@@ -646,7 +670,7 @@ class Server:
# for every sub process...
for proc in process.children(recursive=True):
- # kill all the child processes - it sounds too wrong saying kill all the children (kevdagoat: lol!)
+ # kill all the child processes
logger.info(f"Sending SIGKILL to server {proc.name}")
proc.kill()
# kill the main process we are after
@@ -678,8 +702,9 @@ class Server:
# check the exit code -- This could be a fix for /stop
if self.process.returncode == 0:
logger.warning(
- f"Process {self.process.pid} exited with code {self.process.returncode}. This is considered a clean exit"
- + " supressing crash handling."
+ f"Process {self.process.pid} exited with code "
+ f"{self.process.returncode}. This is considered a clean exit"
+ f" supressing crash handling."
)
# cancel the watcher task
self.server_scheduler.remove_job("c_" + str(self.server_id))
@@ -699,10 +724,12 @@ class Server:
# we have tried to restart 4 times...
elif self.restart_count == 4:
logger.critical(
- f"Server {self.name} has been restarted {self.restart_count} times. It has crashed, not restarting."
+ f"Server {self.name} has been restarted {self.restart_count}"
+ f" times. It has crashed, not restarting."
)
console.critical(
- f"Server {self.name} has been restarted {self.restart_count} times. It has crashed, not restarting."
+ f"Server {self.name} has been restarted {self.restart_count}"
+ f" times. It has crashed, not restarting."
)
self.restart_count = 0
@@ -740,7 +767,8 @@ class Server:
if self.server_path is None:
self.server_path = helper.get_os_understandable_path(self.settings["path"])
logger.info(
- "Backup Thread - Local server path not defined. Setting local server path variable."
+ "Backup Thread - Local server path not defined. "
+ "Setting local server path variable."
)
# checks if the backup thread is currently alive for this server
if not self.is_backingup:
@@ -752,7 +780,8 @@ class Server:
return False
else:
logger.error(
- f"Backup is already being processed for server {self.settings['server_name']}. Canceling backup request"
+ f"Backup is already being processed for server "
+ f"{self.settings['server_name']}. Canceling backup request"
)
return False
logger.info(f"Backup Thread started for server {self.settings['server_name']}.")
@@ -779,10 +808,14 @@ class Server:
conf = management_helper.get_backup_config(self.server_id)
helper.ensure_dir_exists(self.settings["backup_path"])
try:
- backup_filename = f"{self.settings['backup_path']}/{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}"
+ backup_filename = (
+ f"{self.settings['backup_path']}/"
+ f"{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}"
+ )
logger.info(
f"Creating backup of server '{self.settings['server_name']}'"
- + f" (ID#{self.server_id}, path={self.server_path}) at '{backup_filename}'"
+ f" (ID#{self.server_id}, path={self.server_path}) "
+ f"at '{backup_filename}'"
)
tempDir = tempfile.mkdtemp()
@@ -799,14 +832,17 @@ class Server:
server_dir = helper.get_os_understandable_path(self.settings["path"])
for my_dir in excluded_dirs:
- # Take the full path of the excluded dir and replace the server path with the temp path
- # This is so that we're only deleting excluded dirs from the temp path and not the server path
+ # Take the full path of the excluded dir and replace the
+ # server path with the temp path, this is so that we're
+ # only deleting excluded dirs from the temp path
+ # and not the server path
excluded_dir = helper.get_os_understandable_path(my_dir).replace(
server_dir, helper.get_os_understandable_path(tempDir)
)
# Next, check to see if it is a directory
if os.path.isdir(excluded_dir):
- # If it is a directory, recursively delete the entire directory from the backup
+ # If it is a directory,
+ # recursively delete the entire directory from the backup
file_helper.del_dirs(excluded_dir)
else:
# If not, just remove the file
@@ -945,7 +981,8 @@ class Server:
if self.check_running():
wasStarted = True
logger.info(
- f"Server with PID {self.process.pid} is running. Sending shutdown command"
+ f"Server with PID {self.process.pid} is running. "
+ f"Sending shutdown command"
)
self.stop_threaded_server()
else:
@@ -976,7 +1013,8 @@ class Server:
backup_executable = os.path.join(backup_dir, "old_server.jar")
else:
logger.info(
- f"Executable backup directory not found for Server: {self.name}. Creating one."
+ f"Executable backup directory not found for Server: {self.name}."
+ f" Creating one."
)
os.mkdir(backup_dir)
backup_executable = os.path.join(backup_dir, "old_server.jar")
@@ -1062,9 +1100,9 @@ class Server:
)
logger.error("Executable download failed.")
- # ************************************************************************************************
+ # **********************************************************************************
# Minecraft Servers Statistics
- # ************************************************************************************************
+ # **********************************************************************************
def realtime_stats(self):
total_players = 0
@@ -1180,7 +1218,8 @@ class Server:
ping_data = Stats.parse_server_RakNet_ping(int_mc_ping)
else:
ping_data = Stats.parse_server_ping(int_mc_ping)
- # Makes sure we only show stats when a server is online otherwise people have gotten confused.
+ # Makes sure we only show stats when a server is online
+ # otherwise people have gotten confused.
if self.check_running():
server_stats = {
"id": server_id,
@@ -1302,7 +1341,8 @@ class Server:
int_data = False
ping_data = {}
- # Makes sure we only show stats when a server is online otherwise people have gotten confused.
+ # Makes sure we only show stats when a server is online
+ # otherwise people have gotten confused.
if self.check_running():
# if we got a good ping return, let's parse it
if servers_helper.get_server_type_by_id(server_id) != "minecraft-bedrock":
diff --git a/app/classes/shared/tasks.py b/app/classes/shared/tasks.py
index 1b9f5db9..eef4ba73 100644
--- a/app/classes/shared/tasks.py
+++ b/app/classes/shared/tasks.py
@@ -92,7 +92,8 @@ class TasksManager:
svr = self.controller.get_server_obj(c.server_id)
except:
logger.error(
- "Server value requested does note exist purging item from waiting commands."
+ "Server value requested does note exist! "
+ "Purging item from waiting commands."
)
management_helper.mark_command_complete(c.command_id)
@@ -162,7 +163,9 @@ class TasksManager:
def scheduler_thread(self):
schedules = management_helper.get_schedules_enabled()
self.scheduler.add_listener(self.schedule_watcher, mask=EVENT_JOB_EXECUTED)
- # self.scheduler.add_job(self.scheduler.print_jobs, 'interval', seconds=10, id='-1')
+ # self.scheduler.add_job(
+ # self.scheduler.print_jobs, "interval", seconds=10, id="-1"
+ # )
# load schedules from DB
for schedule in schedules:
@@ -254,7 +257,8 @@ class TasksManager:
job_data["parent"],
job_data["delay"],
)
- # Checks to make sure some doofus didn't actually make the newly created task a child of itself.
+ # Checks to make sure some doofus didn't actually make the newly
+ # created task a child of itself.
if str(job_data["parent"]) == str(sch_id):
management_helper.update_scheduled_task(sch_id, {"parent": None})
# Check to see if it's enabled and is not a chain reaction.
@@ -349,12 +353,14 @@ class TasksManager:
else:
logger.info(
f"Job with ID {sch_id} was deleted from DB, but was not enabled."
- + "Not going to try removing something that doesn't exist from active schedules."
+ f"Not going to try removing something "
+ f"that doesn't exist from active schedules."
)
def update_job(self, sch_id, job_data):
management_helper.update_scheduled_task(sch_id, job_data)
- # Checks to make sure some doofus didn't actually make the newly created task a child of itself.
+ # Checks to make sure some doofus didn't actually make the newly
+ # created task a child of itself.
if str(job_data["parent"]) == str(sch_id):
management_helper.update_scheduled_task(sch_id, {"parent": None})
try:
@@ -362,7 +368,8 @@ class TasksManager:
self.scheduler.remove_job(str(sch_id))
except:
logger.info(
- "No job found in update job. Assuming it was previously disabled. Starting new job."
+ "No job found in update job. "
+ "Assuming it was previously disabled. Starting new job."
)
if job_data["enabled"]:
@@ -436,7 +443,8 @@ class TasksManager:
self.scheduler.remove_job(str(sch_id))
except:
logger.info(
- f"APScheduler found no scheduled job on schedule update for schedule with id: {sch_id} Assuming it was already disabled."
+ f"APScheduler found no scheduled job on schedule update for "
+ f"schedule with id: {sch_id} Assuming it was already disabled."
)
def schedule_watcher(self, event):
@@ -454,11 +462,14 @@ class TasksManager:
if task.one_time:
self.remove_job(task.schedule_id)
logger.info("one time task detected. Deleting...")
- # check for any child tasks for this. It's kind of backward, but this makes DB management a lot easier. One to one instead of one to many.
+ # check for any child tasks for this. It's kind of backward,
+ # but this makes DB management a lot easier. One to one
+ # instead of one to many.
for schedule in management_helper.get_child_schedules_by_server(
task.schedule_id, task.server_id
):
- # event job ID's are strings so we need to look at this as the same data type.
+ # event job ID's are strings so we need to look at
+ # this as the same data type.
if str(schedule.parent) == str(event.job_id):
if schedule.enabled:
delaytime = datetime.datetime.now() + datetime.timedelta(
@@ -478,7 +489,8 @@ class TasksManager:
)
else:
logger.info(
- "Event job ID is not numerical. Assuming it's stats - not stored in DB. Moving on."
+ "Event job ID is not numerical. Assuming it's stats "
+ "- not stored in DB. Moving on."
)
else:
logger.error(f"Task failed with error: {event.exception}")
diff --git a/app/classes/web/ajax_handler.py b/app/classes/web/ajax_handler.py
index 77b79828..eca70e88 100644
--- a/app/classes/web/ajax_handler.py
+++ b/app/classes/web/ajax_handler.py
@@ -173,7 +173,8 @@ class AjaxHandler(BaseHandler):
data-path="{dpath}"
data-name="{filename}"
onclick="">
- {filename}"""
+
+ {filename}"""
self.write(helper.get_os_understandable_path(folder) + "\n" + output)
self.finish()
@@ -236,7 +237,8 @@ class AjaxHandler(BaseHandler):
data-path="{dpath}"
data-name="{filename}"
onclick="">
- {filename}"""
+
+ {filename}"""
self.write(helper.get_os_understandable_path(folder) + "\n" + output)
self.finish()
@@ -320,7 +322,9 @@ class AjaxHandler(BaseHandler):
self.controller.management.add_to_audit_log(
exec_user["user_id"],
- f"Sent command to {self.controller.servers.get_server_friendly_name(server_id)} terminal: {command}",
+ f"Sent command to "
+ f"{self.controller.servers.get_server_friendly_name(server_id)} "
+ f"terminal: {command}",
server_id,
self.get_remote_ip(),
)
@@ -516,7 +520,8 @@ class AjaxHandler(BaseHandler):
return
server_id = self.get_argument("id", None)
logger.info(
- f"Removing server from panel for server: {self.controller.servers.get_server_friendly_name(server_id)}"
+ f"Removing server from panel for server: "
+ f"{self.controller.servers.get_server_friendly_name(server_id)}"
)
server_data = self.controller.get_server_data(server_id)
@@ -539,7 +544,8 @@ class AjaxHandler(BaseHandler):
return
server_id = self.get_argument("id", None)
logger.info(
- f"Removing server and all associated files for server: {self.controller.servers.get_server_friendly_name(server_id)}"
+ f"Removing server and all associated files for server: "
+ f"{self.controller.servers.get_server_friendly_name(server_id)}"
)
server_data = self.controller.get_server_data(server_id)
diff --git a/app/classes/web/panel_handler.py b/app/classes/web/panel_handler.py
index fd859ae1..93ec83a9 100644
--- a/app/classes/web/panel_handler.py
+++ b/app/classes/web/panel_handler.py
@@ -1,3 +1,4 @@
+# pylint: disable=too-many-lines
import time
import datetime
import os
@@ -36,7 +37,8 @@ class PanelHandler(BaseHandler):
user_roles = {}
for user in self.controller.users.get_all_users():
user_roles_list = self.controller.users.get_user_roles_names(user.user_id)
- # user_servers = self.controller.servers.get_authorized_servers(user.user_id)
+ # user_servers =
+ # self.controller.servers.get_authorized_servers(user.user_id)
user_roles[user.user_id] = user_roles_list
return user_roles
@@ -142,7 +144,8 @@ class PanelHandler(BaseHandler):
api_key, _, exec_user = self.current_user
superuser = exec_user["superuser"]
- # Commented out because there is no server access control for API keys, they just inherit from the host user
+ # Commented out because there is no server access control for API keys,
+ # they just inherit from the host user
# if api_key is not None:
# superuser = superuser and api_key.superuser
@@ -162,7 +165,8 @@ class PanelHandler(BaseHandler):
server_id, api_key
):
print(
- f"API key {api_key.name} (id: {api_key.token_id}) does not have permission"
+ f"API key {api_key.name} (id: {api_key.token_id}) "
+ f"does not have permission"
)
self.redirect("/panel/error?error=Invalid Server ID")
return None
@@ -434,7 +438,8 @@ class PanelHandler(BaseHandler):
page_servers.append(server)
un_used_servers.remove(server)
user_order.remove(server_id)
- # we only want to set these server stats values once. We need to update the flag so it only hits that if once.
+ # we only want to set these server stats values once.
+ # We need to update the flag so it only hits that if once.
flag += 1
for server in un_used_servers:
@@ -447,7 +452,8 @@ class PanelHandler(BaseHandler):
user_order.remove(server_id)
page_data["servers"] = page_servers
- # num players is set to zero here. If we poll all servers while dashboard is loading it takes FOREVER. We leave this to the
+ # num players is set to zero here. If we poll all servers while
+ # dashboard is loading it takes FOREVER. We leave this to the
# async polling once dashboard is served.
page_data["num_players"] = 0
@@ -778,7 +784,7 @@ class PanelHandler(BaseHandler):
page_data[
"quantity_server"
] = (
- self.controller.crafty_perms.list_all_crafty_permissions_quantity_limits()
+ self.controller.crafty_perms.list_all_crafty_permissions_quantity_limits() # pylint: disable=line-too-long
)
page_data["languages"] = []
page_data["languages"].append(
@@ -843,7 +849,8 @@ class PanelHandler(BaseHandler):
page_data["schedule"]["cron_string"] = ""
page_data["schedule"]["time"] = ""
page_data["schedule"]["interval"] = ""
- # we don't need to check difficulty here. We'll just default to basic for new schedules
+ # we don't need to check difficulty here.
+ # We'll just default to basic for new schedules
page_data["schedule"]["difficulty"] = "basic"
page_data["schedule"]["interval_type"] = "days"
@@ -898,7 +905,8 @@ class PanelHandler(BaseHandler):
"children"
] = self.controller.management.get_child_schedules(sch_id)
# We check here to see if the command is any of the default ones.
- # We do not want a user changing to a custom command and seeing our command there.
+ # We do not want a user changing to a custom command
+ # and seeing our command there.
if (
schedule.action != "start"
or schedule.action != "stop"
@@ -1192,7 +1200,8 @@ class PanelHandler(BaseHandler):
elif page == "support_logs":
logger.info(
- f"Support logs requested. Packinging logs for user with ID: {exec_user['user_id']}"
+ f"Support logs requested. "
+ f"Packinging logs for user with ID: {exec_user['user_id']}"
)
logs_thread = threading.Thread(
target=self.controller.package_support_logs,
@@ -1243,7 +1252,8 @@ class PanelHandler(BaseHandler):
exec_user["user_id"]
)
)
- # defined_servers = self.controller.servers.get_authorized_servers(exec_user["user_id"])
+ # defined_servers =
+ # self.controller.servers.get_authorized_servers(exec_user["user_id"])
for r in exec_user["roles"]:
role = self.controller.roles.get_role(r)
exec_user_role.add(role["role_name"])
@@ -1289,7 +1299,8 @@ class PanelHandler(BaseHandler):
server_obj = self.controller.servers.get_server_obj(server_id)
stale_executable = server_obj.executable
- # Compares old jar name to page data being passed. If they are different we replace the executable name in the
+ # Compares old jar name to page data being passed.
+ # If they are different we replace the executable name in the
if str(stale_executable) != str(executable):
execution_command = execution_command.replace(
str(stale_executable), str(executable)
@@ -1711,7 +1722,8 @@ class PanelHandler(BaseHandler):
elif page == "edit_user":
if bleach.clean(self.get_argument("username", None)) == "system":
self.redirect(
- "/panel/error?error=Unauthorized access: system user is not editable"
+ "/panel/error?error=Unauthorized access: "
+ "system user is not editable"
)
user_id = bleach.clean(self.get_argument("id", None))
username = bleach.clean(self.get_argument("username", None))
@@ -1724,8 +1736,9 @@ class PanelHandler(BaseHandler):
)
if superuser:
- # Checks if user is trying to change super user status of self. We don't want that.
- # Automatically make them stay super user since we know they are.
+ # Checks if user is trying to change super user status of self.
+ # We don't want that. Automatically make them stay super user
+ # since we know they are.
if str(exec_user["user_id"]) != str(user_id):
superuser = bleach.clean(self.get_argument("superuser", "0"))
else:
@@ -1800,7 +1813,8 @@ class PanelHandler(BaseHandler):
self.controller.management.add_to_audit_log(
exec_user["user_id"],
- f"Edited user {username} (UID:{user_id}) with roles {roles} and permissions {permissions_mask}",
+ f"Edited user {username} (UID:{user_id}) with roles {roles} "
+ f"and permissions {permissions_mask}",
server_id=0,
source_ip=self.get_remote_ip(),
)
@@ -1836,8 +1850,9 @@ class PanelHandler(BaseHandler):
self.controller.management.add_to_audit_log(
exec_user["user_id"],
- f"Added API key {name} with crafty permissions {crafty_permissions_mask}"
- + f" and {server_permissions_mask} for user with UID: {user_id}",
+ f"Added API key {name} with crafty permissions "
+ f"{crafty_permissions_mask}"
+ f" and {server_permissions_mask} for user with UID: {user_id}",
server_id=0,
source_ip=self.get_remote_ip(),
)
@@ -1858,7 +1873,8 @@ class PanelHandler(BaseHandler):
self.controller.management.add_to_audit_log(
exec_user["user_id"],
- f"Generated a new API token for the key {key.name} from user with UID: {key.user.user_id}",
+ f"Generated a new API token for the key {key.name} "
+ f"from user with UID: {key.user.user_id}",
server_id=0,
source_ip=self.get_remote_ip(),
)
@@ -1871,8 +1887,9 @@ class PanelHandler(BaseHandler):
elif page == "add_user":
if bleach.clean(self.get_argument("username", None)).lower() == "system":
self.redirect(
- "/panel/error?error=Unauthorized access: username system is reserved for the Crafty system."
- + " Please choose a different username."
+ "/panel/error?error=Unauthorized access: "
+ "username system is reserved for the Crafty system."
+ " Please choose a different username."
)
return
username = bleach.clean(self.get_argument("username", None))
@@ -2074,7 +2091,8 @@ class PanelHandler(BaseHandler):
self.controller.management.add_to_audit_log(
exec_user["user_id"],
- f"Removed API key {target_key} (ID: {key_id}) from user {exec_user['user_id']}",
+ f"Removed API key {target_key} "
+ f"(ID: {key_id}) from user {exec_user['user_id']}",
server_id=0,
source_ip=self.get_remote_ip(),
)
diff --git a/app/classes/web/public_handler.py b/app/classes/web/public_handler.py
index f4d392de..a91482ef 100644
--- a/app/classes/web/public_handler.py
+++ b/app/classes/web/public_handler.py
@@ -127,7 +127,10 @@ class PublicHandler(BaseHandler):
# if they are disabled
if not user_data.enabled:
- error_msg = "User account disabled. Please contact your system administrator for more info."
+ error_msg = (
+ "User account disabled. Please contact "
+ "your system administrator for more info."
+ )
# self.clear_cookie("user")
# self.clear_cookie("user_data")
self.clear_cookie("token")
diff --git a/app/classes/web/server_handler.py b/app/classes/web/server_handler.py
index feb98075..d6507c24 100644
--- a/app/classes/web/server_handler.py
+++ b/app/classes/web/server_handler.py
@@ -126,7 +126,8 @@ class ServerHandler(BaseHandler):
exec_user["user_id"]
):
self.redirect(
- "/panel/error?error=Unauthorized access: not a server creator or server limit reached"
+ "/panel/error?error=Unauthorized access: "
+ "not a server creator or server limit reached"
)
return
@@ -141,7 +142,8 @@ class ServerHandler(BaseHandler):
exec_user["user_id"]
):
self.redirect(
- "/panel/error?error=Unauthorized access: not a server creator or server limit reached"
+ "/panel/error?error=Unauthorized access: "
+ "not a server creator or server limit reached"
)
return
@@ -286,7 +288,7 @@ class ServerHandler(BaseHandler):
)
self.controller.management.add_to_audit_log(
exec_user["user_id"],
- f'imported a jar server named "{server_name}"', # Example: Admin imported a server named "old creative"
+ f'imported a jar server named "{server_name}"',
new_server_id,
self.get_remote_ip(),
)
@@ -303,13 +305,15 @@ class ServerHandler(BaseHandler):
)
if new_server_id == "false":
self.redirect(
- "/panel/error?error=Zip file not accessible! You can fix this permissions issue with"
- + f"sudo chown -R crafty:crafty {import_server_path} And sudo chmod 2775 -R {import_server_path}"
+ f"/panel/error?error=Zip file not accessible! "
+ f"You can fix this permissions issue with "
+ f"sudo chown -R crafty:crafty {import_server_path} "
+ f"And sudo chmod 2775 -R {import_server_path}"
)
return
self.controller.management.add_to_audit_log(
exec_user["user_id"],
- f'imported a zip server named "{server_name}"', # Example: Admin imported a server named "old creative"
+ f'imported a zip server named "{server_name}"',
new_server_id,
self.get_remote_ip(),
)
@@ -320,20 +324,23 @@ class ServerHandler(BaseHandler):
self.redirect("/panel/error?error=Invalid server data")
return
server_type, server_version = server_parts
- # TODO: add server type check here and call the correct server add functions if not a jar
+ # TODO: add server type check here and call the correct server
+ # add functions if not a jar
role_ids = self.controller.users.get_user_roles_id(exec_user["user_id"])
new_server_id = self.controller.create_jar_server(
server_type, server_version, server_name, min_mem, max_mem, port
)
self.controller.management.add_to_audit_log(
exec_user["user_id"],
- f'created a {server_version} {str(server_type).capitalize()} server named "{server_name}"',
+ f"created a {server_version} {str(server_type).capitalize()}"
+ f' server named "{server_name}"',
# Example: Admin created a 1.16.5 Bukkit server named "survival"
new_server_id,
self.get_remote_ip(),
)
- # These lines create a new Role for the Server with full permissions and add the user to it if he's not a superuser
+ # These lines create a new Role for the Server with full permissions
+ # and add the user to it if he's not a superuser
if len(captured_roles) == 0:
if not superuser:
new_server_uuid = self.controller.servers.get_server_data_by_id(
@@ -399,7 +406,7 @@ class ServerHandler(BaseHandler):
)
self.controller.management.add_to_audit_log(
exec_user["user_id"],
- f'imported a jar server named "{server_name}"', # Example: Admin imported a server named "old creative"
+ f'imported a jar server named "{server_name}"',
new_server_id,
self.get_remote_ip(),
)
@@ -416,13 +423,15 @@ class ServerHandler(BaseHandler):
)
if new_server_id == "false":
self.redirect(
- "/panel/error?error=Zip file not accessible! You can fix this permissions issue with"
- + f"sudo chown -R crafty:crafty {import_server_path} And sudo chmod 2775 -R {import_server_path}"
+ f"/panel/error?error=Zip file not accessible! "
+ f"You can fix this permissions issue with"
+ f"sudo chown -R crafty:crafty {import_server_path} "
+ f"And sudo chmod 2775 -R {import_server_path}"
)
return
self.controller.management.add_to_audit_log(
exec_user["user_id"],
- f'imported a zip server named "{server_name}"', # Example: Admin imported a server named "old creative"
+ f'imported a zip server named "{server_name}"',
new_server_id,
self.get_remote_ip(),
)
@@ -433,20 +442,23 @@ class ServerHandler(BaseHandler):
self.redirect("/panel/error?error=Invalid server data")
return
server_type, server_version = server_parts
- # TODO: add server type check here and call the correct server add functions if not a jar
+ # TODO: add server type check here and call the correct server
+ # add functions if not a jar
role_ids = self.controller.users.get_user_roles_id(exec_user["user_id"])
new_server_id = self.controller.create_jar_server(
server_type, server_version, server_name, min_mem, max_mem, port
)
self.controller.management.add_to_audit_log(
exec_user["user_id"],
- f'created a {server_version} {str(server_type).capitalize()} server named "{server_name}"',
+ f"created a {server_version} {str(server_type).capitalize()} "
+ f'server named "{server_name}"',
# Example: Admin created a 1.16.5 Bukkit server named "survival"
new_server_id,
self.get_remote_ip(),
)
- # These lines create a new Role for the Server with full permissions and add the user to it if he's not a superuser
+ # These lines create a new Role for the Server with full permissions
+ # and add the user to it if he's not a superuser
if len(captured_roles) == 0:
if not superuser:
new_server_uuid = self.controller.servers.get_server_data_by_id(
diff --git a/app/classes/web/tornado_handler.py b/app/classes/web/tornado_handler.py
index ad62629c..805820ac 100644
--- a/app/classes/web/tornado_handler.py
+++ b/app/classes/web/tornado_handler.py
@@ -61,12 +61,15 @@ class Webserver:
@staticmethod
def _asyncio_patch():
"""
- As of Python 3.8 (on Windows), the asyncio default event handler has changed to "proactor",
+ As of Python 3.8 (on Windows),
+ the asyncio default event handler has changed to "proactor",
where tornado expects the "selector" handler.
- This function checks if the platform is windows and changes the event handler to suit.
+ This function checks if the platform is windows and
+ changes the event handler to suit.
- (Taken from https://github.com/mkdocs/mkdocs/commit/cf2b136d4257787c0de51eba2d9e30ded5245b31)
+ (Taken from
+ https://github.com/mkdocs/mkdocs/commit/cf2b136d4257787c0de51eba2d9e30ded5245b31)
"""
logger.debug("Checking if asyncio patch is required")
if sys.platform.startswith("win") and sys.version_info >= (3, 8):
@@ -189,10 +192,12 @@ class Webserver:
self.HTTPS_Server.listen(https_port)
logger.info(
- f"https://{helper.get_local_ip()}:{https_port} is up and ready for connections."
+ f"https://{helper.get_local_ip()}:{https_port} "
+ f"is up and ready for connections."
)
console.info(
- f"https://{helper.get_local_ip()}:{https_port} is up and ready for connections."
+ f"https://{helper.get_local_ip()}:{https_port} "
+ f"is up and ready for connections."
)
console.info("Server Init Complete: Listening For Connections:")
diff --git a/app/classes/web/upload_handler.py b/app/classes/web/upload_handler.py
index 9a6e71a0..5ebcfff0 100644
--- a/app/classes/web/upload_handler.py
+++ b/app/classes/web/upload_handler.py
@@ -75,10 +75,12 @@ class UploadHandler(BaseHandler):
if Enum_Permissions_Server.Files not in exec_user_server_permissions:
logger.warning(
- f"User {user_id} tried to upload a file to {server_id} without permissions!"
+ f"User {user_id} tried to upload a file to "
+ f"{server_id} without permissions!"
)
console.warning(
- f"User {user_id} tried to upload a file to {server_id} without permissions!"
+ f"User {user_id} tried to upload a file to "
+ f"{server_id} without permissions!"
)
self.do_upload = False
@@ -101,10 +103,12 @@ class UploadHandler(BaseHandler):
full_path,
)
logger.warning(
- f"User {user_id} tried to upload a file to {server_id} but the path is not inside of the server!"
+ f"User {user_id} tried to upload a file to {server_id} "
+ f"but the path is not inside of the server!"
)
console.warning(
- f"User {user_id} tried to upload a file to {server_id} but the path is not inside of the server!"
+ f"User {user_id} tried to upload a file to {server_id} "
+ f"but the path is not inside of the server!"
)
self.do_upload = False
diff --git a/app/classes/web/websocket_helper.py b/app/classes/web/websocket_helper.py
index 9d39659b..5e4f3289 100644
--- a/app/classes/web/websocket_helper.py
+++ b/app/classes/web/websocket_helper.py
@@ -24,14 +24,16 @@ class WebSocketHelper:
def broadcast(self, event_type: str, data):
logger.debug(
- f"Sending to {len(self.clients)} clients: {json.dumps({'event': event_type, 'data': data})}"
+ f"Sending to {len(self.clients)} clients: "
+ f"{json.dumps({'event': event_type, 'data': data})}"
)
for client in self.clients:
try:
self.send_message(client, event_type, data)
except Exception as e:
logger.exception(
- f"Error caught while sending WebSocket message to {client.get_remote_ip()} {e}"
+ f"Error caught while sending WebSocket message to "
+ f"{client.get_remote_ip()} {e}"
)
def broadcast_page(self, page: str, event_type: str, data):
@@ -85,7 +87,8 @@ class WebSocketHelper:
def broadcast_with_fn(self, filter_fn, event_type: str, data):
clients = list(filter(filter_fn, self.clients))
logger.debug(
- f"Sending to {len(clients)} out of {len(self.clients)} clients: {json.dumps({'event': event_type, 'data': data})}"
+ f"Sending to {len(clients)} out of {len(self.clients)} "
+ f"clients: {json.dumps({'event': event_type, 'data': data})}"
)
for client in clients:
@@ -93,7 +96,8 @@ class WebSocketHelper:
self.send_message(client, event_type, data)
except Exception as e:
logger.exception(
- f"Error catched while sending WebSocket message to {client.get_remote_ip()} {e}"
+ f"Error catched while sending WebSocket message to "
+ f"{client.get_remote_ip()} {e}"
)
def disconnect_all(self):