fix fstrings, refactored console to static

This commit is contained in:
computergeek125 2022-04-11 20:34:46 -05:00
parent b5cac0e385
commit d417950eae
17 changed files with 190 additions and 198 deletions

View File

@ -9,13 +9,13 @@ import uuid
import random import random
from app.classes.minecraft.bedrock_ping import BedrockPing from app.classes.minecraft.bedrock_ping import BedrockPing
from app.classes.shared.console import Console
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
class Server: class Server:
def __init__(self, console, data): def __init__(self, data):
self.console = console
self.description = data.get("description") self.description = data.get("description")
# print(self.description) # print(self.description)
if isinstance(self.description, dict): if isinstance(self.description, dict):
@ -32,19 +32,19 @@ class Server:
if "extra" in description.keys(): if "extra" in description.keys():
for e in description["extra"]: for e in description["extra"]:
# Conversion format code needed only for Java Version # Conversion format code needed only for Java Version
lines.append(get_code_format(self.console, "reset")) lines.append(get_code_format("reset"))
if "bold" in e.keys(): if "bold" in e.keys():
lines.append(get_code_format(self.console, "bold")) lines.append(get_code_format("bold"))
if "italic" in e.keys(): if "italic" in e.keys():
lines.append(get_code_format(self.console, "italic")) lines.append(get_code_format("italic"))
if "underlined" in e.keys(): if "underlined" in e.keys():
lines.append(get_code_format(self.console, "underlined")) lines.append(get_code_format("underlined"))
if "strikethrough" in e.keys(): if "strikethrough" in e.keys():
lines.append(get_code_format(self.console, "strikethrough")) lines.append(get_code_format("strikethrough"))
if "obfuscated" in e.keys(): if "obfuscated" in e.keys():
lines.append(get_code_format(self.console, "obfuscated")) lines.append(get_code_format("obfuscated"))
if "color" in e.keys(): if "color" in e.keys():
lines.append(get_code_format(self.console, e["color"])) lines.append(get_code_format(e["color"]))
# Then append the text # Then append the text
if "text" in e.keys(): if "text" in e.keys():
if e["text"] == "\n": if e["text"] == "\n":
@ -95,7 +95,7 @@ class Player:
return self.name return self.name
def get_code_format(console, format_name): def get_code_format(format_name):
root_dir = os.path.abspath(os.path.curdir) root_dir = os.path.abspath(os.path.curdir)
format_file = os.path.join(root_dir, "app", "config", "motd_format.json") format_file = os.path.join(root_dir, "app", "config", "motd_format.json")
try: try:
@ -106,14 +106,14 @@ def get_code_format(console, format_name):
return data.get(format_name) return data.get(format_name)
else: else:
logger.error(f"Format MOTD Error: format name {format_name} does not exist") logger.error(f"Format MOTD Error: format name {format_name} does not exist")
console.error( Console.error(
f"Format MOTD Error: format name {format_name} does not exist" f"Format MOTD Error: format name {format_name} does not exist"
) )
return "" return ""
except Exception as e: except Exception as e:
logger.critical(f"Config File Error: Unable to read {format_file} due to {e}") logger.critical(f"Config File Error: Unable to read {format_file} due to {e}")
console.critical(f"Config File Error: Unable to read {format_file} due to {e}") Console.critical(f"Config File Error: Unable to read {format_file} due to {e}")
return "" return ""

View File

@ -133,7 +133,7 @@ class Stats:
internal_ip = server["server_ip"] internal_ip = server["server_ip"]
server_port = server["server_port"] server_port = server["server_port"]
logger.debug("Pinging {internal_ip} on port {server_port}") logger.debug(f"Pinging {internal_ip} on port {server_port}")
if helper_servers.get_server_type_by_id(server_id) != "minecraft-bedrock": if helper_servers.get_server_type_by_id(server_id) != "minecraft-bedrock":
int_mc_ping = ping(internal_ip, int(server_port)) int_mc_ping = ping(internal_ip, int(server_port))

View File

@ -3,6 +3,7 @@ import cmd
import time import time
import threading import threading
import logging import logging
from app.classes.shared.console import Console
from app.classes.shared.import3 import import3 from app.classes.shared.import3 import import3
@ -13,7 +14,6 @@ class MainPrompt(cmd.Cmd):
def __init__(self, helper, tasks_manager, migration_manager): def __init__(self, helper, tasks_manager, migration_manager):
super().__init__() super().__init__()
self.helper = helper self.helper = helper
self.console = self.helper.console
self.tasks_manager = tasks_manager self.tasks_manager = tasks_manager
self.migration_manager = migration_manager self.migration_manager = migration_manager
# overrides the default Prompt # overrides the default Prompt
@ -34,20 +34,20 @@ class MainPrompt(cmd.Cmd):
elif line == "down": elif line == "down":
self.migration_manager.down() self.migration_manager.down()
elif line == "done": elif line == "done":
self.console.info(self.migration_manager.done) Console.info(self.migration_manager.done)
elif line == "todo": elif line == "todo":
self.console.info(self.migration_manager.todo) Console.info(self.migration_manager.todo)
elif line == "diff": elif line == "diff":
self.console.info(self.migration_manager.diff) Console.info(self.migration_manager.diff)
elif line == "info": elif line == "info":
self.console.info(f"Done: {self.migration_manager.done}") Console.info(f"Done: {self.migration_manager.done}")
self.console.info(f"FS: {self.migration_manager.todo}") Console.info(f"FS: {self.migration_manager.todo}")
self.console.info(f"Todo: {self.migration_manager.diff}") Console.info(f"Todo: {self.migration_manager.diff}")
elif line.startswith("add "): elif line.startswith("add "):
migration_name = line[len("add ") :] migration_name = line[len("add ") :]
self.migration_manager.create(migration_name, False) self.migration_manager.create(migration_name, False)
else: else:
self.console.info("Unknown migration command") Console.info("Unknown migration command")
@staticmethod @staticmethod
def do_threads(_line): def do_threads(_line):
@ -65,21 +65,21 @@ class MainPrompt(cmd.Cmd):
def universal_exit(self): def universal_exit(self):
logger.info("Stopping all server daemons / threads") logger.info("Stopping all server daemons / threads")
self.console.info( Console.info(
"Stopping all server daemons / threads - This may take a few seconds" "Stopping all server daemons / threads - This may take a few seconds"
) )
self.helper.websocket_helper.disconnect_all() self.helper.websocket_helper.disconnect_all()
self.console.info("Waiting for main thread to stop") Console.info("Waiting for main thread to stop")
while True: while True:
if self.tasks_manager.get_main_thread_run_status(): if self.tasks_manager.get_main_thread_run_status():
sys.exit(0) sys.exit(0)
time.sleep(1) time.sleep(1)
def help_exit(self): def help_exit(self):
self.console.help("Stops the server if running, Exits the program") Console.help("Stops the server if running, Exits the program")
def help_migrations(self): def help_migrations(self):
self.console.help("Only for advanced users. Use with caution") Console.help("Only for advanced users. Use with caution")
def help_import3(self): def help_import3(self):
self.console.help("Import users and servers from Crafty 3") Console.help("Import users and servers from Crafty 3")

View File

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

View File

@ -19,6 +19,7 @@ from socket import gethostname
from contextlib import suppress from contextlib import suppress
import psutil import psutil
from app.classes.shared.console import Console
from app.classes.shared.installer import installer from app.classes.shared.installer import installer
from app.classes.shared.file_helpers import FileHelpers from app.classes.shared.file_helpers import FileHelpers
from app.classes.shared.translation import Translation from app.classes.shared.translation import Translation
@ -41,8 +42,7 @@ except ModuleNotFoundError as err:
class Helpers: class Helpers:
allowed_quotes = ['"', "'", "`"] allowed_quotes = ['"', "'", "`"]
def __init__(self, console): def __init__(self):
self.console = console
self.root_dir = os.path.abspath(os.path.curdir) self.root_dir = os.path.abspath(os.path.curdir)
self.config_dir = os.path.join(self.root_dir, "app", "config") self.config_dir = os.path.join(self.root_dir, "app", "config")
self.webroot = os.path.join(self.root_dir, "app", "frontend") self.webroot = os.path.join(self.root_dir, "app", "frontend")
@ -200,14 +200,14 @@ class Helpers:
else: else:
logger.error(f"Config File Error: setting {key} does not exist") logger.error(f"Config File Error: setting {key} does not exist")
self.console.error(f"Config File Error: setting {key} does not exist") Console.error(f"Config File Error: setting {key} does not exist")
return default_return return default_return
except Exception as e: except Exception as e:
logger.critical( logger.critical(
f"Config File Error: Unable to read {self.settings_file} due to {e}" f"Config File Error: Unable to read {self.settings_file} due to {e}"
) )
self.console.critical( Console.critical(
f"Config File Error: Unable to read {self.settings_file} due to {e}" f"Config File Error: Unable to read {self.settings_file} due to {e}"
) )
@ -224,7 +224,7 @@ class Helpers:
else: else:
logger.error(f"Config File Error: setting {key} does not exist") logger.error(f"Config File Error: setting {key} does not exist")
self.console.error(f"Config File Error: setting {key} does not exist") Console.error(f"Config File Error: setting {key} does not exist")
return default_return return default_return
with open(self.settings_file, "w", encoding="utf-8") as f: with open(self.settings_file, "w", encoding="utf-8") as f:
@ -234,7 +234,7 @@ class Helpers:
logger.critical( logger.critical(
f"Config File Error: Unable to read {self.settings_file} due to {e}" f"Config File Error: Unable to read {self.settings_file} due to {e}"
) )
self.console.critical( Console.critical(
f"Config File Error: Unable to read {self.settings_file} due to {e}" f"Config File Error: Unable to read {self.settings_file} due to {e}"
) )
@ -260,7 +260,7 @@ class Helpers:
version_data = json.load(f) version_data = json.load(f)
except Exception as e: except Exception as e:
self.console.critical(f"Unable to get version data! \n{e}") Console.critical(f"Unable to get version data! \n{e}")
return version_data return version_data
@ -470,13 +470,13 @@ class Helpers:
with suppress(FileExistsError): with suppress(FileExistsError):
os.makedirs(os.path.join(self.root_dir, "logs")) os.makedirs(os.path.join(self.root_dir, "logs"))
except Exception as e: except Exception as e:
self.console.error(f"Failed to make logs directory with error: {e} ") Console.error(f"Failed to make logs directory with error: {e} ")
# ensure the log file is there # ensure the log file is there
try: try:
open(log_file, "a", encoding="utf-8").close() open(log_file, "a", encoding="utf-8").close()
except Exception as e: except Exception as e:
self.console.critical(f"Unable to open log file! {e}") Console.critical(f"Unable to open log file! {e}")
sys.exit(1) sys.exit(1)
# del any old session.lock file as this is a new session # del any old session.lock file as this is a new session
@ -576,7 +576,7 @@ class Helpers:
pid = data.get("pid") pid = data.get("pid")
started = data.get("started") started = data.get("started")
if psutil.pid_exists(pid): if psutil.pid_exists(pid):
self.console.critical( Console.critical(
f"Another Crafty Controller agent seems to be running..." f"Another Crafty Controller agent seems to be running..."
f"\npid: {pid} \nstarted on: {started}" f"\npid: {pid} \nstarted on: {started}"
) )
@ -591,7 +591,7 @@ class Helpers:
except Exception as e: except Exception as e:
logger.error(f"Failed to locate existing session.lock with error: {e} ") logger.error(f"Failed to locate existing session.lock with error: {e} ")
self.console.error( Console.error(
f"Failed to locate existing session.lock with error: {e} " f"Failed to locate existing session.lock with error: {e} "
) )
@ -693,12 +693,12 @@ class Helpers:
logger.info("Cert and Key files already exists, not creating them.") logger.info("Cert and Key files already exists, not creating them.")
return True return True
self.console.info("Generating a self signed SSL") Console.info("Generating a self signed SSL")
logger.info("Generating a self signed SSL") logger.info("Generating a self signed SSL")
# create a key pair # create a key pair
logger.info("Generating a key pair. This might take a moment.") logger.info("Generating a key pair. This might take a moment.")
self.console.info("Generating a key pair. This might take a moment.") Console.info("Generating a key pair. This might take a moment.")
k = crypto.PKey() k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 4096) k.generate_key(crypto.TYPE_RSA, 4096)

View File

@ -3,6 +3,7 @@ import os
import logging import logging
from app.classes.controllers.users_controller import helper_users from app.classes.controllers.users_controller import helper_users
from app.classes.shared.console import Console
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -10,7 +11,6 @@ logger = logging.getLogger(__name__)
class import3: class import3:
def __init__(self, helper, controller): def __init__(self, helper, controller):
self.helper = helper self.helper = helper
self.console = self.helper.console
self.controller = controller self.controller = controller
def start_import(self): def start_import(self):
@ -21,13 +21,11 @@ class import3:
) )
) )
if not os.path.exists(folder): if not os.path.exists(folder):
self.console.info( Console.info(
"Crafty cannot find the path you entered. " "Crafty cannot find the path you entered. "
"Does Crafty's user have permission to access it?" "Does Crafty's user have permission to access it?"
) )
self.console.info( Console.info("Please run the import3 command again and enter a valid path.")
"Please run the import3 command again and enter a valid path."
)
else: else:
with open(os.path.join(folder, "users.json"), encoding="utf-8") as f: with open(os.path.join(folder, "users.json"), encoding="utf-8") as f:
user_json = json.loads(f.read()) user_json = json.loads(f.read())
@ -41,10 +39,10 @@ class import3:
if isinstance(json_data, list): if isinstance(json_data, list):
for user in json_data: for user in json_data:
helper_users.add_rawpass_user(user["username"], user["password"]) helper_users.add_rawpass_user(user["username"], user["password"])
self.console.info(f"Imported user {user['username']} from Crafty 3") Console.info(f"Imported user {user['username']} from Crafty 3")
logger.info(f"Imported user {user['username']} from Crafty 3") logger.info(f"Imported user {user['username']} from Crafty 3")
else: else:
self.console.info( Console.info(
"There is only one user detected. " "There is only one user detected. "
"Cannot create duplicate Admin account." "Cannot create duplicate Admin account."
) )
@ -65,7 +63,7 @@ class import3:
max_mem=(int(server["memory_max"]) / 1000), max_mem=(int(server["memory_max"]) / 1000),
port=server["server_port"], port=server["server_port"],
) )
self.console.info( Console.info(
f"Imported server {server['server_name']}[{server['id']}] " f"Imported server {server['server_name']}[{server['id']}] "
f"from Crafty 3 to new server id {new_server_id}" f"from Crafty 3 to new server id {new_server_id}"
) )
@ -82,7 +80,7 @@ class import3:
max_mem=(int(json_data["memory_max"]) / 1000), max_mem=(int(json_data["memory_max"]) / 1000),
port=json_data["server_port"], port=json_data["server_port"],
) )
self.console.info( Console.info(
f"Imported server {json_data['server_name']}[{json_data['id']}] " f"Imported server {json_data['server_name']}[{json_data['id']}] "
f"from Crafty 3 to new server id {new_server_id}" f"from Crafty 3 to new server id {new_server_id}"
) )

View File

@ -23,6 +23,7 @@ from app.classes.models.users import helper_users
from app.classes.models.management import helpers_management from app.classes.models.management import helpers_management
from app.classes.models.servers import helper_servers from app.classes.models.servers import helper_servers
from app.classes.shared.authentication import Authentication from app.classes.shared.authentication import Authentication
from app.classes.shared.console import Console
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
from app.classes.shared.server import Server from app.classes.shared.server import Server
from app.classes.shared.file_helpers import FileHelpers from app.classes.shared.file_helpers import FileHelpers
@ -36,7 +37,6 @@ logger = logging.getLogger(__name__)
class Controller: class Controller:
def __init__(self, database, helper): def __init__(self, database, helper):
self.helper = helper self.helper = helper
self.console = self.helper.console
self.server_jars = ServerJars(helper) self.server_jars = ServerJars(helper)
self.users_helper = helper_users(database, self.helper) self.users_helper = helper_users(database, self.helper)
self.servers_helper = helper_servers(database) self.servers_helper = helper_servers(database)
@ -94,7 +94,7 @@ class Controller:
f"Skipping this server" f"Skipping this server"
) )
self.console.warning( Console.warning(
f"Unable to find server {s['server_name']} at path {s['path']}. " f"Unable to find server {s['server_name']} at path {s['path']}. "
f"Skipping this server" f"Skipping this server"
) )
@ -107,9 +107,7 @@ class Controller:
# if the properties file isn't there, let's warn # if the properties file isn't there, let's warn
if not Helpers.check_file_exists(settings_file): if not Helpers.check_file_exists(settings_file):
logger.error(f"Unable to find {settings_file}. Skipping this server.") logger.error(f"Unable to find {settings_file}. Skipping this server.")
self.console.error( Console.error(f"Unable to find {settings_file}. Skipping this server.")
f"Unable to find {settings_file}. Skipping this server."
)
continue continue
settings = ServerProps(settings_file) settings = ServerProps(settings_file)
@ -132,7 +130,7 @@ class Controller:
self.refresh_server_settings(s["server_id"]) self.refresh_server_settings(s["server_id"])
self.console.info( Console.info(
f"Loaded Server: ID {s['server_id']}" f"Loaded Server: ID {s['server_id']}"
+ f" | Name: {s['server_name']}" + f" | Name: {s['server_name']}"
+ f" | Autostart: {s['auto_start']}" + f" | Autostart: {s['auto_start']}"
@ -314,14 +312,14 @@ class Controller:
def stop_all_servers(self): def stop_all_servers(self):
servers = self.list_running_servers() servers = self.list_running_servers()
logger.info(f"Found {len(servers)} running server(s)") logger.info(f"Found {len(servers)} running server(s)")
self.console.info(f"Found {len(servers)} running server(s)") Console.info(f"Found {len(servers)} running server(s)")
logger.info("Stopping All Servers") logger.info("Stopping All Servers")
self.console.info("Stopping All Servers") Console.info("Stopping All Servers")
for s in servers: for s in servers:
logger.info(f"Stopping Server ID {s['id']} - {s['name']}") logger.info(f"Stopping Server ID {s['id']} - {s['name']}")
self.console.info(f"Stopping Server ID {s['id']} - {s['name']}") Console.info(f"Stopping Server ID {s['id']} - {s['name']}")
self.stop_server(s["id"]) self.stop_server(s["id"])
@ -329,7 +327,7 @@ class Controller:
time.sleep(2) time.sleep(2)
logger.info("All Servers Stopped") logger.info("All Servers Stopped")
self.console.info("All Servers Stopped") Console.info("All Servers Stopped")
def stop_server(self, server_id): def stop_server(self, server_id):
# issue the stop command # issue the stop command
@ -807,9 +805,7 @@ class Controller:
server_name = server_data["server_name"] server_name = server_data["server_name"]
logger.info(f"Deleting Server: ID {server_id} | Name: {server_name} ") logger.info(f"Deleting Server: ID {server_id} | Name: {server_name} ")
self.console.info( Console.info(f"Deleting Server: ID {server_id} | Name: {server_name} ")
f"Deleting Server: ID {server_id} | Name: {server_name} "
)
srv_obj = s["server_obj"] srv_obj = s["server_obj"]
running = srv_obj.check_running() running = srv_obj.check_running()

View File

@ -16,6 +16,7 @@ from playhouse.migrate import (
make_index_name, make_index_name,
) )
from app.classes.shared.console import Console
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -398,13 +399,13 @@ class MigrationManager(object):
Runs all unapplied migrations. Runs all unapplied migrations.
""" """
logger.info("Starting migrations") logger.info("Starting migrations")
self.helper.console.info("Starting migrations") Console.info("Starting migrations")
done = [] done = []
diff = self.diff diff = self.diff
if not diff: if not diff:
logger.info("There is nothing to migrate") logger.info("There is nothing to migrate")
self.helper.console.info("There is nothing to migrate") Console.info("There is nothing to migrate")
return done return done
migrator = self.migrator migrator = self.migrator

View File

@ -20,6 +20,7 @@ from app.classes.models.servers import Server_Stats, helper_servers
from app.classes.models.management import helpers_management from app.classes.models.management import helpers_management
from app.classes.models.users import helper_users from app.classes.models.users import helper_users
from app.classes.models.server_permissions import Permissions_Servers from app.classes.models.server_permissions import Permissions_Servers
from app.classes.shared.console import Console
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
from app.classes.shared.file_helpers import FileHelpers from app.classes.shared.file_helpers import FileHelpers
@ -93,7 +94,6 @@ class Server:
def __init__(self, helper, management_helper, stats): def __init__(self, helper, management_helper, stats):
self.helper = helper self.helper = helper
self.management_helper = management_helper self.management_helper = management_helper
self.console = self.helper.console
# holders for our process # holders for our process
self.process = None self.process = None
self.line = False self.line = False
@ -149,9 +149,7 @@ class Server:
delay = int(self.settings["auto_start_delay"]) delay = int(self.settings["auto_start_delay"])
logger.info(f"Scheduling server {self.name} to start in {delay} seconds") logger.info(f"Scheduling server {self.name} to start in {delay} seconds")
self.console.info( Console.info(f"Scheduling server {self.name} to start in {delay} seconds")
f"Scheduling server {self.name} to start in {delay} seconds"
)
self.server_scheduler.add_job( self.server_scheduler.add_job(
self.run_scheduled_server, self.run_scheduled_server,
@ -161,7 +159,7 @@ class Server:
) )
def run_scheduled_server(self): def run_scheduled_server(self):
self.console.info(f"Starting server ID: {self.server_id} - {self.name}") Console.info(f"Starting server ID: {self.server_id} - {self.name}")
logger.info(f"Starting server ID: {self.server_id} - {self.name}") logger.info(f"Starting server ID: {self.server_id} - {self.name}")
# Sets waiting start to false since we're attempting to start the server. # Sets waiting start to false since we're attempting to start the server.
helper_servers.set_waiting_start(self.server_id, False) helper_servers.set_waiting_start(self.server_id, False)
@ -182,7 +180,7 @@ class Server:
# Register an shedule for polling server stats when running # Register an shedule for polling server stats when running
logger.info(f"Polling server statistics {self.name} every {5} seconds") logger.info(f"Polling server statistics {self.name} every {5} seconds")
self.console.info(f"Polling server statistics {self.name} every {5} seconds") Console.info(f"Polling server statistics {self.name} every {5} seconds")
try: try:
self.server_scheduler.add_job( self.server_scheduler.add_job(
self.realtime_stats, self.realtime_stats,
@ -213,19 +211,17 @@ class Server:
logger.critical( logger.critical(
f"Server executable path: {full_path} does not seem to exist" f"Server executable path: {full_path} does not seem to exist"
) )
self.console.critical( Console.critical(
f"Server executable path: {full_path} does not seem to exist" f"Server executable path: {full_path} does not seem to exist"
) )
if not Helpers.check_path_exists(self.server_path): if not Helpers.check_path_exists(self.server_path):
logger.critical(f"Server path: {self.server_path} does not seem to exits") logger.critical(f"Server path: {self.server_path} does not seem to exits")
self.console.critical( Console.critical(f"Server path: {self.server_path} does not seem to exits")
f"Server path: {self.server_path} does not seem to exits"
)
if not Helpers.check_writeable(self.server_path): if not Helpers.check_writeable(self.server_path):
logger.critical(f"Unable to write/access {self.server_path}") logger.critical(f"Unable to write/access {self.server_path}")
self.console.critical(f"Unable to write/access {self.server_path}") Console.critical(f"Unable to write/access {self.server_path}")
def start_server(self, user_id): def start_server(self, user_id):
if not user_id: if not user_id:
@ -253,16 +249,14 @@ class Server:
# fail safe in case we try to start something already running # fail safe in case we try to start something already running
if self.check_running(): if self.check_running():
logger.error("Server is already running - Cancelling Startup") logger.error("Server is already running - Cancelling Startup")
self.console.error("Server is already running - Cancelling Startup") Console.error("Server is already running - Cancelling Startup")
return False return False
if self.check_update(): if self.check_update():
logger.error("Server is updating. Terminating startup.") logger.error("Server is updating. Terminating startup.")
return False return False
logger.info(f"Launching Server {self.name} with command {self.server_command}") logger.info(f"Launching Server {self.name} with command {self.server_command}")
self.console.info( Console.info(f"Launching Server {self.name} with command {self.server_command}")
f"Launching Server {self.name} with command {self.server_command}"
)
# Checks for eula. Creates one if none detected. # Checks for eula. Creates one if none detected.
# If EULA is detected and not set to true we offer to set it true. # If EULA is detected and not set to true we offer to set it true.
@ -424,7 +418,7 @@ class Server:
if self.process.poll() is None: if self.process.poll() is None:
logger.info(f"Server {self.name} running with PID {self.process.pid}") logger.info(f"Server {self.name} running with PID {self.process.pid}")
self.console.info(f"Server {self.name} running with PID {self.process.pid}") Console.info(f"Server {self.name} running with PID {self.process.pid}")
self.is_crashed = False self.is_crashed = False
helper_servers.server_crash_reset(self.server_id) helper_servers.server_crash_reset(self.server_id)
self.record_server_stats() self.record_server_stats()
@ -471,7 +465,7 @@ class Server:
f"Server PID {self.process.pid} died right after starting " f"Server PID {self.process.pid} died right after starting "
f"- is this a server config issue?" f"- is this a server config issue?"
) )
self.console.critical( Console.critical(
f"Server PID {self.process.pid} died right after starting " f"Server PID {self.process.pid} died right after starting "
f"- is this a server config issue?" f"- is this a server config issue?"
) )
@ -481,7 +475,7 @@ class Server:
f"Server {self.name} has crash detection enabled " f"Server {self.name} has crash detection enabled "
f"- starting watcher task" f"- starting watcher task"
) )
self.console.info( Console.info(
f"Server {self.name} has crash detection enabled " f"Server {self.name} has crash detection enabled "
f"- starting watcher task" f"- starting watcher task"
) )
@ -524,7 +518,7 @@ class Server:
f"Server {self.name} has crash detection enabled " f"Server {self.name} has crash detection enabled "
f"- starting watcher task" f"- starting watcher task"
) )
self.console.info( Console.info(
f"Server {self.name} has crash detection enabled " f"Server {self.name} has crash detection enabled "
"- starting watcher task" "- starting watcher task"
) )
@ -557,7 +551,7 @@ class Server:
running = self.check_running() running = self.check_running()
if not running: if not running:
logger.info(f"Can't stop server {self.name} if it's not running") logger.info(f"Can't stop server {self.name} if it's not running")
self.console.info(f"Can't stop server {self.name} if it's not running") Console.info(f"Can't stop server {self.name} if it's not running")
return return
x = 0 x = 0
@ -573,7 +567,7 @@ class Server:
f"seconds until force close)" f"seconds until force close)"
) )
logger.info(logstr) logger.info(logstr)
self.console.info(logstr) Console.info(logstr)
running = self.check_running() running = self.check_running()
time.sleep(2) time.sleep(2)
@ -582,13 +576,13 @@ class Server:
logger.info( logger.info(
f"Server {server_name} is still running - Forcing the process down" f"Server {server_name} is still running - Forcing the process down"
) )
self.console.info( Console.info(
f"Server {server_name} is still running - Forcing the process down" f"Server {server_name} is still running - Forcing the process down"
) )
self.kill() self.kill()
logger.info(f"Stopped Server {server_name} with PID {server_pid}") logger.info(f"Stopped Server {server_name} with PID {server_pid}")
self.console.info(f"Stopped Server {server_name} with PID {server_pid}") Console.info(f"Stopped Server {server_name} with PID {server_pid}")
# massive resetting of variables # massive resetting of variables
self.cleanup_server_object() self.cleanup_server_object()
@ -633,7 +627,7 @@ class Server:
if not self.check_running() and command.lower() != "start": if not self.check_running() and command.lower() != "start":
logger.warning(f'Server not running, unable to send command "{command}"') logger.warning(f'Server not running, unable to send command "{command}"')
return False return False
self.console.info(f"COMMAND TIME: {command}") Console.info(f"COMMAND TIME: {command}")
logger.debug(f"Sending command {command} to server") logger.debug(f"Sending command {command} to server")
# send it # send it
@ -657,7 +651,7 @@ class Server:
f"The server {name} has crashed and will be restarted. " f"The server {name} has crashed and will be restarted. "
f"Restarting server" f"Restarting server"
) )
self.console.critical( Console.critical(
f"The server {name} has crashed and will be restarted. " f"The server {name} has crashed and will be restarted. "
f"Restarting server" f"Restarting server"
) )
@ -668,7 +662,7 @@ class Server:
f"The server {name} has crashed, " f"The server {name} has crashed, "
f"crash detection is disabled and it will not be restarted" f"crash detection is disabled and it will not be restarted"
) )
self.console.critical( Console.critical(
f"The server {name} has crashed, " f"The server {name} has crashed, "
f"crash detection is disabled and it will not be restarted" f"crash detection is disabled and it will not be restarted"
) )
@ -737,7 +731,7 @@ class Server:
f"Server {self.name} has been restarted {self.restart_count}" f"Server {self.name} has been restarted {self.restart_count}"
f" times. It has crashed, not restarting." f" times. It has crashed, not restarting."
) )
self.console.critical( Console.critical(
f"Server {self.name} has been restarted {self.restart_count}" f"Server {self.name} has been restarted {self.restart_count}"
f" times. It has crashed, not restarting." f" times. It has crashed, not restarting."
) )
@ -751,7 +745,7 @@ class Server:
def remove_watcher_thread(self): def remove_watcher_thread(self):
logger.info("Removing old crash detection watcher thread") logger.info("Removing old crash detection watcher thread")
self.console.info("Removing old crash detection watcher thread") Console.info("Removing old crash detection watcher thread")
self.server_scheduler.remove_job("c_" + str(self.server_id)) self.server_scheduler.remove_job("c_" + str(self.server_id))
def agree_eula(self, user_id): def agree_eula(self, user_id):
@ -1184,7 +1178,7 @@ class Server:
"/status", "update_server_status", servers_ping "/status", "update_server_status", servers_ping
) )
except: except:
self.console.critical("Can't broadcast server status to websocket") Console.critical("Can't broadcast server status to websocket")
def get_servers_stats(self): def get_servers_stats(self):
@ -1211,7 +1205,7 @@ class Server:
server_port = server["server_port"] server_port = server["server_port"]
server_name = server.get("server_name", f"ID#{server_id}") server_name = server.get("server_name", f"ID#{server_id}")
logger.debug("Pinging server '{server}' on {internal_ip}:{server_port}") logger.debug(f"Pinging server '{server}' on {internal_ip}:{server_port}")
if helper_servers.get_server_type_by_id(server_id) == "minecraft-bedrock": if helper_servers.get_server_type_by_id(server_id) == "minecraft-bedrock":
int_mc_ping = ping_bedrock(internal_ip, int(server_port)) int_mc_ping = ping_bedrock(internal_ip, int(server_port))
else: else:
@ -1285,7 +1279,7 @@ class Server:
internal_ip = server["server_ip"] internal_ip = server["server_ip"]
server_port = server["server_port"] server_port = server["server_port"]
logger.debug("Pinging {internal_ip} on port {server_port}") logger.debug(f"Pinging {internal_ip} on port {server_port}")
if helper_servers.get_server_type_by_id(self.server_id) != "minecraft-bedrock": if helper_servers.get_server_type_by_id(self.server_id) != "minecraft-bedrock":
int_mc_ping = ping(internal_ip, int(server_port)) int_mc_ping = ping(internal_ip, int(server_port))

View File

@ -11,6 +11,7 @@ from apscheduler.triggers.cron import CronTrigger
from app.classes.models.management import helpers_management from app.classes.models.management import helpers_management
from app.classes.models.users import helper_users from app.classes.models.users import helper_users
from app.classes.shared.console import Console
from app.classes.web.tornado_handler import Webserver from app.classes.web.tornado_handler import Webserver
logger = logging.getLogger("apscheduler") logger = logging.getLogger("apscheduler")
@ -119,7 +120,7 @@ class TasksManager:
logger.info("Caught error during shutdown", exc_info=True) logger.info("Caught error during shutdown", exc_info=True)
logger.info("***** Crafty Shutting Down *****\n\n") logger.info("***** Crafty Shutting Down *****\n\n")
self.helper.console.info("***** Crafty Shutting Down *****\n\n") Console.info("***** Crafty Shutting Down *****\n\n")
self.main_thread_exiting = True self.main_thread_exiting = True
def start_webserver(self): def start_webserver(self):
@ -127,7 +128,7 @@ class TasksManager:
def reload_webserver(self): def reload_webserver(self):
self.tornado.stop_web_server() self.tornado.stop_web_server()
self.helper.console.info("Waiting 3 seconds") Console.info("Waiting 3 seconds")
time.sleep(3) time.sleep(3)
self.webserver_thread = threading.Thread( self.webserver_thread = threading.Thread(
target=self.tornado.run_tornado, daemon=True, name="tornado_thread" target=self.tornado.run_tornado, daemon=True, name="tornado_thread"
@ -139,16 +140,16 @@ class TasksManager:
def start_scheduler(self): def start_scheduler(self):
logger.info("Launching Scheduler Thread...") logger.info("Launching Scheduler Thread...")
self.helper.console.info("Launching Scheduler Thread...") Console.info("Launching Scheduler Thread...")
self.schedule_thread.start() self.schedule_thread.start()
logger.info("Launching command thread...") logger.info("Launching command thread...")
self.helper.console.info("Launching command thread...") Console.info("Launching command thread...")
self.command_thread.start() self.command_thread.start()
logger.info("Launching log watcher...") logger.info("Launching log watcher...")
self.helper.console.info("Launching log watcher...") Console.info("Launching log watcher...")
self.log_watcher_thread.start() self.log_watcher_thread.start()
logger.info("Launching realtime thread...") logger.info("Launching realtime thread...")
self.helper.console.info("Launching realtime thread...") Console.info("Launching realtime thread...")
self.realtime_thread.start() self.realtime_thread.start()
def scheduler_thread(self): def scheduler_thread(self):
@ -177,10 +178,8 @@ class TasksManager:
], ],
) )
except Exception as e: except Exception as e:
self.helper.console.error( Console.error(f"Failed to schedule task with error: {e}.")
f"Failed to schedule task with error: {e}." Console.warning("Removing failed task from DB.")
)
self.helper.console.warning("Removing failed task from DB.")
logger.error(f"Failed to schedule task with error: {e}.") logger.error(f"Failed to schedule task with error: {e}.")
logger.warning("Removing failed task from DB.") logger.warning("Removing failed task from DB.")
# remove items from DB if task fails to add to apscheduler # remove items from DB if task fails to add to apscheduler
@ -274,10 +273,8 @@ class TasksManager:
], ],
) )
except Exception as e: except Exception as e:
self.helper.console.error( Console.error(f"Failed to schedule task with error: {e}.")
f"Failed to schedule task with error: {e}." Console.warning("Removing failed task from DB.")
)
self.helper.console.warning("Removing failed task from DB.")
logger.error(f"Failed to schedule task with error: {e}.") logger.error(f"Failed to schedule task with error: {e}.")
logger.warning("Removing failed task from DB.") logger.warning("Removing failed task from DB.")
# remove items from DB if task fails to add to apscheduler # remove items from DB if task fails to add to apscheduler
@ -387,10 +384,8 @@ class TasksManager:
], ],
) )
except Exception as e: except Exception as e:
self.helper.console.error( Console.error(f"Failed to schedule task with error: {e}.")
f"Failed to schedule task with error: {e}." Console.info("Removing failed task from DB.")
)
self.helper.console.info("Removing failed task from DB.")
self.controller.management_helper.delete_scheduled_task(sch_id) self.controller.management_helper.delete_scheduled_task(sch_id)
else: else:
if job_data["interval_type"] == "hours": if job_data["interval_type"] == "hours":
@ -499,7 +494,7 @@ class TasksManager:
logger.info( logger.info(
f"Stats collection frequency set to {stats_update_frequency} seconds" f"Stats collection frequency set to {stats_update_frequency} seconds"
) )
self.helper.console.info( Console.info(
f"Stats collection frequency set to {stats_update_frequency} seconds" f"Stats collection frequency set to {stats_update_frequency} seconds"
) )

View File

@ -3,6 +3,8 @@ import logging
import os import os
import typing as t import typing as t
from app.classes.shared.console import Console
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -59,7 +61,7 @@ class Translation:
f"Translation File Error: page {page} " f"Translation File Error: page {page} "
f"does not exist for lang {language}" f"does not exist for lang {language}"
) )
self.helper.console.error( Console.error(
f"Translation File Error: page {page} " f"Translation File Error: page {page} "
f"does not exist for lang {language}" f"does not exist for lang {language}"
) )
@ -73,7 +75,7 @@ class Translation:
f"Translation File Error: word {word} does not exist on page " f"Translation File Error: word {word} does not exist on page "
f"{page} for lang {language}" f"{page} for lang {language}"
) )
self.helper.console.error( Console.error(
f"Translation File Error: word {word} does not exist on page " f"Translation File Error: word {word} does not exist on page "
f"{page} for lang {language}" f"{page} for lang {language}"
) )
@ -83,7 +85,7 @@ class Translation:
logger.critical( logger.critical(
f"Translation File Error: Unable to read {language_file} due to {e}" f"Translation File Error: Unable to read {language_file} due to {e}"
) )
self.helper.console.critical( Console.critical(
f"Translation File Error: Unable to read {language_file} due to {e}" f"Translation File Error: Unable to read {language_file} due to {e}"
) )
return None return None

View File

@ -8,6 +8,7 @@ import tornado.web
import tornado.escape import tornado.escape
from app.classes.models.server_permissions import Enum_Permissions_Server from app.classes.models.server_permissions import Enum_Permissions_Server
from app.classes.shared.console import Console
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
from app.classes.shared.server import ServerOutBuf from app.classes.shared.server import ServerOutBuf
from app.classes.web.base_handler import BaseHandler from app.classes.web.base_handler import BaseHandler
@ -283,9 +284,7 @@ class AjaxHandler(BaseHandler):
if server_id is None: if server_id is None:
logger.warning("Server ID not found in send_command ajax call") logger.warning("Server ID not found in send_command ajax call")
self.helper.console.warning( Console.warning("Server ID not found in send_command ajax call")
"Server ID not found in send_command ajax call"
)
srv_obj = self.controller.get_server_obj(server_id) srv_obj = self.controller.get_server_obj(server_id)
@ -484,7 +483,7 @@ class AjaxHandler(BaseHandler):
) )
server_id = self.get_argument("id", None) server_id = self.get_argument("id", None)
self.helper.console.warning(f"Delete {file_path} for server {server_id}") Console.warning(f"Delete {file_path} for server {server_id}")
if not self.check_server_id(server_id, "del_backup"): if not self.check_server_id(server_id, "del_backup"):
return return
@ -502,9 +501,7 @@ class AjaxHandler(BaseHandler):
) )
) or not Helpers.check_file_exists(os.path.abspath(file_path)): ) or not Helpers.check_file_exists(os.path.abspath(file_path)):
logger.warning(f"Invalid path in del_backup ajax call ({file_path})") logger.warning(f"Invalid path in del_backup ajax call ({file_path})")
self.helper.console.warning( Console.warning(f"Invalid path in del_backup ajax call ({file_path})")
f"Invalid path in del_backup ajax call ({file_path})"
)
return return
# Delete the file # Delete the file
@ -567,7 +564,7 @@ class AjaxHandler(BaseHandler):
logger.warning( logger.warning(
f"Server ID not defined in {page_name} ajax call ({server_id})" f"Server ID not defined in {page_name} ajax call ({server_id})"
) )
self.helper.console.warning( Console.warning(
f"Server ID not defined in {page_name} ajax call ({server_id})" f"Server ID not defined in {page_name} ajax call ({server_id})"
) )
return return
@ -579,7 +576,7 @@ class AjaxHandler(BaseHandler):
logger.warning( logger.warning(
f"Server ID not found in {page_name} ajax call ({server_id})" f"Server ID not found in {page_name} ajax call ({server_id})"
) )
self.helper.console.warning( Console.warning(
f"Server ID not found in {page_name} ajax call ({server_id})" f"Server ID not found in {page_name} ajax call ({server_id})"
) )
return return

View File

@ -5,6 +5,7 @@ import tornado.web
import tornado.escape import tornado.escape
from app.classes.models.server_permissions import Enum_Permissions_Server from app.classes.models.server_permissions import Enum_Permissions_Server
from app.classes.shared.console import Console
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
from app.classes.shared.file_helpers import FileHelpers from app.classes.shared.file_helpers import FileHelpers
from app.classes.web.base_handler import BaseHandler from app.classes.web.base_handler import BaseHandler
@ -66,7 +67,7 @@ class FileHandler(BaseHandler):
logger.warning( logger.warning(
f"Invalid path in get_file file file ajax call ({file_path})" f"Invalid path in get_file file file ajax call ({file_path})"
) )
self.helper.self.helper.console.warning( Console.warning(
f"Invalid path in get_file file file ajax call ({file_path})" f"Invalid path in get_file file file ajax call ({file_path})"
) )
return return
@ -175,7 +176,7 @@ class FileHandler(BaseHandler):
logger.warning( logger.warning(
f"Invalid path in create_file file ajax call ({file_path})" f"Invalid path in create_file file ajax call ({file_path})"
) )
self.helper.self.helper.console.warning( Console.warning(
f"Invalid path in create_file file ajax call ({file_path})" f"Invalid path in create_file file ajax call ({file_path})"
) )
return return
@ -209,7 +210,7 @@ class FileHandler(BaseHandler):
logger.warning( logger.warning(
f"Invalid path in create_dir file ajax call ({dir_path})" f"Invalid path in create_dir file ajax call ({dir_path})"
) )
self.helper.self.helper.console.warning( Console.warning(
f"Invalid path in create_dir file ajax call ({dir_path})" f"Invalid path in create_dir file ajax call ({dir_path})"
) )
return return
@ -257,9 +258,7 @@ class FileHandler(BaseHandler):
self.get_body_argument("file_path", default=None, strip=True) self.get_body_argument("file_path", default=None, strip=True)
) )
self.helper.self.helper.console.warning( Console.warning(f"Delete {file_path} for server {server_id}")
f"Delete {file_path} for server {server_id}"
)
if not self.check_server_id(server_id, "del_file"): if not self.check_server_id(server_id, "del_file"):
return return
@ -277,7 +276,7 @@ class FileHandler(BaseHandler):
) )
) or not Helpers.check_file_exists(os.path.abspath(file_path)): ) or not Helpers.check_file_exists(os.path.abspath(file_path)):
logger.warning(f"Invalid path in del_file file ajax call ({file_path})") logger.warning(f"Invalid path in del_file file ajax call ({file_path})")
self.helper.console.warning( Console.warning(
f"Invalid path in del_file file ajax call ({file_path})" f"Invalid path in del_file file ajax call ({file_path})"
) )
return return
@ -294,7 +293,7 @@ class FileHandler(BaseHandler):
self.get_body_argument("dir_path", default=None, strip=True) self.get_body_argument("dir_path", default=None, strip=True)
) )
self.helper.console.warning(f"Delete {dir_path} for server {server_id}") Console.warning(f"Delete {dir_path} for server {server_id}")
if not self.check_server_id(server_id, "del_dir"): if not self.check_server_id(server_id, "del_dir"):
return return
@ -306,9 +305,7 @@ class FileHandler(BaseHandler):
Helpers.get_os_understandable_path(server_info["path"]), dir_path Helpers.get_os_understandable_path(server_info["path"]), dir_path
) or not Helpers.check_path_exists(os.path.abspath(dir_path)): ) or not Helpers.check_path_exists(os.path.abspath(dir_path)):
logger.warning(f"Invalid path in del_file file ajax call ({dir_path})") logger.warning(f"Invalid path in del_file file ajax call ({dir_path})")
self.helper.console.warning( Console.warning(f"Invalid path in del_file file ajax call ({dir_path})")
f"Invalid path in del_file file ajax call ({dir_path})"
)
return return
# Delete the directory # Delete the directory
@ -366,7 +363,7 @@ class FileHandler(BaseHandler):
logger.warning( logger.warning(
f"Invalid path in save_file file ajax call ({file_path})" f"Invalid path in save_file file ajax call ({file_path})"
) )
self.helper.console.warning( Console.warning(
f"Invalid path in save_file file ajax call ({file_path})" f"Invalid path in save_file file ajax call ({file_path})"
) )
return return
@ -394,9 +391,7 @@ class FileHandler(BaseHandler):
if item_path is None or new_item_name is None: if item_path is None or new_item_name is None:
logger.warning("Invalid path(s) in rename_file file ajax call") logger.warning("Invalid path(s) in rename_file file ajax call")
self.helper.console.warning( Console.warning("Invalid path(s) in rename_file file ajax call")
"Invalid path(s) in rename_file file ajax call"
)
return return
if not Helpers.in_path( if not Helpers.in_path(
@ -408,7 +403,7 @@ class FileHandler(BaseHandler):
logger.warning( logger.warning(
f"Invalid old name path in rename_file file ajax call ({server_id})" f"Invalid old name path in rename_file file ajax call ({server_id})"
) )
self.helper.console.warning( Console.warning(
f"Invalid old name path in rename_file file ajax call ({server_id})" f"Invalid old name path in rename_file file ajax call ({server_id})"
) )
return return
@ -424,7 +419,7 @@ class FileHandler(BaseHandler):
logger.warning( logger.warning(
f"Invalid new name path in rename_file file ajax call ({server_id})" f"Invalid new name path in rename_file file ajax call ({server_id})"
) )
self.helper.console.warning( Console.warning(
f"Invalid new name path in rename_file file ajax call ({server_id})" f"Invalid new name path in rename_file file ajax call ({server_id})"
) )
return return
@ -472,9 +467,7 @@ class FileHandler(BaseHandler):
if item_path is None or new_item_name is None: if item_path is None or new_item_name is None:
logger.warning("Invalid path(s) in rename_file file ajax call") logger.warning("Invalid path(s) in rename_file file ajax call")
self.helper.console.warning( Console.warning("Invalid path(s) in rename_file file ajax call")
"Invalid path(s) in rename_file file ajax call"
)
return return
if not Helpers.in_path( if not Helpers.in_path(
@ -486,7 +479,7 @@ class FileHandler(BaseHandler):
logger.warning( logger.warning(
f"Invalid old name path in rename_file file ajax call ({server_id})" f"Invalid old name path in rename_file file ajax call ({server_id})"
) )
self.helper.console.warning( Console.warning(
f"Invalid old name path in rename_file file ajax call ({server_id})" f"Invalid old name path in rename_file file ajax call ({server_id})"
) )
return return
@ -502,7 +495,7 @@ class FileHandler(BaseHandler):
logger.warning( logger.warning(
f"Invalid new name path in rename_file file ajax call ({server_id})" f"Invalid new name path in rename_file file ajax call ({server_id})"
) )
self.helper.console.warning( Console.warning(
f"Invalid new name path in rename_file file ajax call ({server_id})" f"Invalid new name path in rename_file file ajax call ({server_id})"
) )
return return
@ -515,7 +508,7 @@ class FileHandler(BaseHandler):
logger.warning( logger.warning(
f"Server ID not defined in {page_name} file ajax call ({server_id})" f"Server ID not defined in {page_name} file ajax call ({server_id})"
) )
self.helper.console.warning( Console.warning(
f"Server ID not defined in {page_name} file ajax call ({server_id})" f"Server ID not defined in {page_name} file ajax call ({server_id})"
) )
return return
@ -527,7 +520,7 @@ class FileHandler(BaseHandler):
logger.warning( logger.warning(
f"Server ID not found in {page_name} file ajax call ({server_id})" f"Server ID not found in {page_name} file ajax call ({server_id})"
) )
self.helper.console.warning( Console.warning(
f"Server ID not found in {page_name} file ajax call ({server_id})" f"Server ID not found in {page_name} file ajax call ({server_id})"
) )
return return

View File

@ -11,6 +11,7 @@ import tornado.escape
import tornado.locale import tornado.locale
import tornado.httpserver import tornado.httpserver
from app.classes.shared.console import Console
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
from app.classes.web.file_handler import FileHandler from app.classes.web.file_handler import FileHandler
from app.classes.web.public_handler import PublicHandler from app.classes.web.public_handler import PublicHandler
@ -211,21 +212,21 @@ class Webserver:
f"https://{Helpers.get_local_ip()}:{https_port} " f"https://{Helpers.get_local_ip()}:{https_port} "
f"is up and ready for connections." f"is up and ready for connections."
) )
self.helper.console.info( Console.info(
f"https://{Helpers.get_local_ip()}:{https_port} " f"https://{Helpers.get_local_ip()}:{https_port} "
f"is up and ready for connections." f"is up and ready for connections."
) )
self.helper.console.info("Server Init Complete: Listening For Connections:") Console.info("Server Init Complete: Listening For Connections:")
self.ioloop = tornado.ioloop.IOLoop.current() self.ioloop = tornado.ioloop.IOLoop.current()
self.ioloop.start() self.ioloop.start()
def stop_web_server(self): def stop_web_server(self):
logger.info("Shutting Down Web Server") logger.info("Shutting Down Web Server")
self.helper.console.info("Shutting Down Web Server") Console.info("Shutting Down Web Server")
self.ioloop.stop() self.ioloop.stop()
self.HTTP_Server.stop() self.HTTP_Server.stop()
self.HTTPS_Server.stop() self.HTTPS_Server.stop()
logger.info("Web Server Stopped") logger.info("Web Server Stopped")
self.helper.console.info("Web Server Stopped") Console.info("Web Server Stopped")

View File

@ -6,6 +6,7 @@ import tornado.options
import tornado.httpserver import tornado.httpserver
from app.classes.models.server_permissions import Enum_Permissions_Server from app.classes.models.server_permissions import Enum_Permissions_Server
from app.classes.shared.console import Console
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
from app.classes.shared.main_controller import Controller from app.classes.shared.main_controller import Controller
from app.classes.web.base_handler import BaseHandler from app.classes.web.base_handler import BaseHandler
@ -82,12 +83,12 @@ class UploadHandler(BaseHandler):
if user_id is None: if user_id is None:
logger.warning("User ID not found in upload handler call") logger.warning("User ID not found in upload handler call")
self.helper.console.warning("User ID not found in upload handler call") Console.warning("User ID not found in upload handler call")
self.do_upload = False self.do_upload = False
if server_id is None: if server_id is None:
logger.warning("Server ID not found in upload handler call") logger.warning("Server ID not found in upload handler call")
self.helper.console.warning("Server ID not found in upload handler call") Console.warning("Server ID not found in upload handler call")
self.do_upload = False self.do_upload = False
if Enum_Permissions_Server.Files not in exec_user_server_permissions: if Enum_Permissions_Server.Files not in exec_user_server_permissions:
@ -95,7 +96,7 @@ class UploadHandler(BaseHandler):
f"User {user_id} tried to upload a file to " f"User {user_id} tried to upload a file to "
f"{server_id} without permissions!" f"{server_id} without permissions!"
) )
self.helper.console.warning( Console.warning(
f"User {user_id} tried to upload a file to " f"User {user_id} tried to upload a file to "
f"{server_id} without permissions!" f"{server_id} without permissions!"
) )
@ -123,7 +124,7 @@ class UploadHandler(BaseHandler):
f"User {user_id} tried to upload a file to {server_id} " f"User {user_id} tried to upload a file to {server_id} "
f"but the path is not inside of the server!" f"but the path is not inside of the server!"
) )
self.helper.console.warning( Console.warning(
f"User {user_id} tried to upload a file to {server_id} " f"User {user_id} tried to upload a file to {server_id} "
f"but the path is not inside of the server!" f"but the path is not inside of the server!"
) )

View File

@ -1,6 +1,8 @@
import json import json
import logging import logging
from app.classes.shared.console import Console
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -100,7 +102,7 @@ class WebSocketHelper:
) )
def disconnect_all(self): def disconnect_all(self):
self.helper.console.info("Disconnecting WebSocket clients") Console.info("Disconnecting WebSocket clients")
for client in self.clients: for client in self.clients:
client.close() client.close()
self.helper.console.info("Disconnected WebSocket clients") Console.info("Disconnected WebSocket clients")

30
main.py
View File

@ -11,14 +11,14 @@ from app.classes.shared.console import Console
from app.classes.shared.helpers import Helpers from app.classes.shared.helpers import Helpers
console = Console() console = Console()
helper = Helpers(console) helper = Helpers()
if helper.checkRoot(): if helper.checkRoot():
console.critical( Console.critical(
"Root detected. Root/Admin access denied. " "Root detected. Root/Admin access denied. "
"Run Crafty again with non-elevated permissions." "Run Crafty again with non-elevated permissions."
) )
time.sleep(5) time.sleep(5)
console.critical("Crafty shutting down. Root/Admin access denied.") Console.critical("Crafty shutting down. Root/Admin access denied.")
sys.exit(0) sys.exit(0)
# pylint: disable=wrong-import-position # pylint: disable=wrong-import-position
try: try:
@ -46,7 +46,7 @@ def do_intro():
{'/' * 75} {'/' * 75}
""" """
console.magenta(intro) Console.magenta(intro)
def setup_logging(debug=True): def setup_logging(debug=True):
@ -64,7 +64,7 @@ def setup_logging(debug=True):
else: else:
logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.DEBUG)
logging.warning(f"Unable to read logging config from {logging_config_file}") logging.warning(f"Unable to read logging config from {logging_config_file}")
console.critical(f"Unable to read logging config from {logging_config_file}") Console.critical(f"Unable to read logging config from {logging_config_file}")
# Our Main Starter # Our Main Starter
@ -94,7 +94,7 @@ if __name__ == "__main__":
# setting up the logger object # setting up the logger object
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
console.cyan(f"Logging set to: {logger.level}") Console.cyan(f"Logging set to: {logger.level}")
peewee_logger = logging.getLogger("peewee") peewee_logger = logging.getLogger("peewee")
peewee_logger.setLevel(logging.INFO) peewee_logger.setLevel(logging.INFO)
@ -119,8 +119,8 @@ if __name__ == "__main__":
fresh_install = installer.is_fresh_install() fresh_install = installer.is_fresh_install()
if fresh_install: if fresh_install:
console.debug("Fresh install detected") Console.debug("Fresh install detected")
console.warning( Console.warning(
f"We have detected a fresh install. Please be sure to forward " f"We have detected a fresh install. Please be sure to forward "
f"Crafty's port, {helper.get_setting('https_port')}, " f"Crafty's port, {helper.get_setting('https_port')}, "
f"through your router/firewall if you would like to be able " f"through your router/firewall if you would like to be able "
@ -128,7 +128,7 @@ if __name__ == "__main__":
) )
installer.default_settings() installer.default_settings()
else: else:
console.debug("Existing install detected") Console.debug("Existing install detected")
# now the tables are created, we can load the tasks_manger and server controller # now the tables are created, we can load the tasks_manger and server controller
controller = Controller(database, helper) controller = Controller(database, helper)
@ -140,7 +140,7 @@ if __name__ == "__main__":
# init servers # init servers
logger.info("Initializing all servers defined") logger.info("Initializing all servers defined")
console.info("Initializing all servers defined") Console.info("Initializing all servers defined")
controller.init_all_servers() controller.init_all_servers()
servers = controller.list_defined_servers() servers = controller.list_defined_servers()
@ -156,10 +156,10 @@ if __name__ == "__main__":
tasks_manager.serverjar_cache_refresher() tasks_manager.serverjar_cache_refresher()
logger.info("Checking Internet. This may take a minute.") logger.info("Checking Internet. This may take a minute.")
console.info("Checking Internet. This may take a minute.") Console.info("Checking Internet. This may take a minute.")
if not helper.check_internet(): if not helper.check_internet():
console.warning( Console.warning(
"We have detected the machine running Crafty has no " "We have detected the machine running Crafty has no "
"connection to the internet. Client connections to " "connection to the internet. Client connections to "
"the server may be limited." "the server may be limited."
@ -180,7 +180,7 @@ if __name__ == "__main__":
logger.info( logger.info(
f"Recieved {signal.Signals(sig[0]).name} [{sig[0]}], stopping Crafty..." f"Recieved {signal.Signals(sig[0]).name} [{sig[0]}], stopping Crafty..."
) )
console.info( Console.info(
f"Recieved {signal.Signals(sig[0]).name} [{sig[0]}], stopping Crafty..." f"Recieved {signal.Signals(sig[0]).name} [{sig[0]}], stopping Crafty..."
) )
tasks_manager._main_graceful_exit() tasks_manager._main_graceful_exit()
@ -194,7 +194,7 @@ if __name__ == "__main__":
except KeyboardInterrupt: except KeyboardInterrupt:
print() # for newline print() # for newline
logger.info("Recieved SIGINT, stopping Crafty...") logger.info("Recieved SIGINT, stopping Crafty...")
console.info("Recieved SIGINT, stopping Crafty...") Console.info("Recieved SIGINT, stopping Crafty...")
tasks_manager._main_graceful_exit() tasks_manager._main_graceful_exit()
Crafty.universal_exit() Crafty.universal_exit()
else: else:
@ -206,7 +206,7 @@ if __name__ == "__main__":
time.sleep(1) time.sleep(1)
except KeyboardInterrupt: except KeyboardInterrupt:
logger.info("Recieved SIGINT, stopping Crafty...") logger.info("Recieved SIGINT, stopping Crafty...")
console.info("Recieved SIGINT, stopping Crafty...") Console.info("Recieved SIGINT, stopping Crafty...")
break break
tasks_manager._main_graceful_exit() tasks_manager._main_graceful_exit()
Crafty.universal_exit() Crafty.universal_exit()