2022-06-13 21:16:49 +00:00
|
|
|
import contextlib
|
2020-08-12 00:36:09 +00:00
|
|
|
import os
|
2020-09-02 01:30:39 +00:00
|
|
|
import re
|
2020-08-12 00:36:09 +00:00
|
|
|
import sys
|
|
|
|
import json
|
2021-08-19 20:50:18 +00:00
|
|
|
import tempfile
|
2020-08-23 22:43:28 +00:00
|
|
|
import time
|
2020-08-12 00:36:09 +00:00
|
|
|
import uuid
|
|
|
|
import string
|
|
|
|
import base64
|
|
|
|
import socket
|
2022-06-03 13:05:26 +00:00
|
|
|
import secrets
|
2020-08-12 00:36:09 +00:00
|
|
|
import logging
|
2021-01-15 12:33:17 +00:00
|
|
|
import html
|
2021-03-22 04:02:18 +00:00
|
|
|
import zipfile
|
|
|
|
import pathlib
|
2021-11-29 21:56:17 +00:00
|
|
|
import ctypes
|
2022-06-20 17:05:39 +00:00
|
|
|
import subprocess
|
2022-06-20 22:44:33 +00:00
|
|
|
import itertools
|
2020-08-12 00:36:09 +00:00
|
|
|
from datetime import datetime
|
|
|
|
from socket import gethostname
|
2022-05-28 16:00:25 +00:00
|
|
|
from contextlib import redirect_stderr, suppress
|
2022-09-12 19:34:47 +00:00
|
|
|
import libgravatar
|
2022-07-20 23:39:29 +00:00
|
|
|
from packaging import version as pkg_version
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-05-28 16:00:25 +00:00
|
|
|
from app.classes.shared.null_writer import NullWriter
|
2022-04-12 01:34:46 +00:00
|
|
|
from app.classes.shared.console import Console
|
2022-03-08 04:40:44 +00:00
|
|
|
from app.classes.shared.installer import installer
|
2022-04-11 05:23:55 +00:00
|
|
|
from app.classes.shared.translation import Translation
|
|
|
|
from app.classes.web.websocket_helper import WebSocketHelper
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-05-28 16:00:25 +00:00
|
|
|
with redirect_stderr(NullWriter()):
|
|
|
|
import psutil
|
|
|
|
|
2022-06-15 04:42:29 +00:00
|
|
|
# winreg is only a package on windows-python. We will only import
|
|
|
|
# this on windows systems to avoid a module not found error
|
|
|
|
# this is only needed for windows java path shenanigans
|
|
|
|
if os.name == "nt":
|
|
|
|
import winreg
|
|
|
|
|
2022-03-08 05:44:26 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2020-08-12 00:36:09 +00:00
|
|
|
try:
|
2020-09-23 01:42:41 +00:00
|
|
|
import requests
|
2022-03-08 04:40:44 +00:00
|
|
|
from requests import get
|
2020-08-12 00:36:09 +00:00
|
|
|
from OpenSSL import crypto
|
2020-08-13 01:33:36 +00:00
|
|
|
from argon2 import PasswordHasher
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-01-26 01:45:30 +00:00
|
|
|
except ModuleNotFoundError as err:
|
2022-03-08 05:44:26 +00:00
|
|
|
logger.critical(f"Import Error: Unable to load {err.name} module", exc_info=True)
|
|
|
|
print(f"Import Error: Unable to load {err.name} module")
|
|
|
|
installer.do_install()
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-03-23 02:50:12 +00:00
|
|
|
|
2020-08-12 00:36:09 +00:00
|
|
|
class Helpers:
|
2022-03-23 02:50:12 +00:00
|
|
|
allowed_quotes = ['"', "'", "`"]
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-04-12 01:34:46 +00:00
|
|
|
def __init__(self):
|
2020-08-12 00:36:09 +00:00
|
|
|
self.root_dir = os.path.abspath(os.path.curdir)
|
2022-03-23 02:50:12 +00:00
|
|
|
self.config_dir = os.path.join(self.root_dir, "app", "config")
|
|
|
|
self.webroot = os.path.join(self.root_dir, "app", "frontend")
|
|
|
|
self.servers_dir = os.path.join(self.root_dir, "servers")
|
|
|
|
self.backup_path = os.path.join(self.root_dir, "backups")
|
|
|
|
self.migration_dir = os.path.join(self.root_dir, "app", "migrations")
|
|
|
|
|
|
|
|
self.session_file = os.path.join(self.root_dir, "app", "config", "session.lock")
|
|
|
|
self.settings_file = os.path.join(self.root_dir, "app", "config", "config.json")
|
|
|
|
|
|
|
|
self.ensure_dir_exists(os.path.join(self.root_dir, "app", "config", "db"))
|
|
|
|
self.db_path = os.path.join(
|
|
|
|
self.root_dir, "app", "config", "db", "crafty.sqlite"
|
|
|
|
)
|
|
|
|
self.serverjar_cache = os.path.join(self.config_dir, "serverjars.json")
|
|
|
|
self.credits_cache = os.path.join(self.config_dir, "credits.json")
|
2020-08-13 01:33:36 +00:00
|
|
|
self.passhasher = PasswordHasher()
|
2020-08-12 00:36:09 +00:00
|
|
|
self.exiting = False
|
|
|
|
|
2022-04-11 05:23:55 +00:00
|
|
|
self.websocket_helper = WebSocketHelper(self)
|
|
|
|
self.translation = Translation(self)
|
2022-08-05 01:37:21 +00:00
|
|
|
self.update_available = False
|
2023-01-27 22:36:23 +00:00
|
|
|
self.ignored_names = ["crafty_managed.txt", "db_stats"]
|
2022-04-11 05:23:55 +00:00
|
|
|
|
2022-03-08 04:40:44 +00:00
|
|
|
@staticmethod
|
|
|
|
def auto_installer_fix(ex):
|
|
|
|
logger.critical(f"Import Error: Unable to load {ex.name} module", exc_info=True)
|
|
|
|
print(f"Import Error: Unable to load {ex.name} module")
|
|
|
|
installer.do_install()
|
|
|
|
|
2022-07-20 22:53:31 +00:00
|
|
|
def check_remote_version(self):
|
|
|
|
"""
|
|
|
|
Check if the remote version is newer than the local version
|
|
|
|
Returning remote version if it is newer, otherwise False.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
# Get tags from Gitlab, select the latest and parse the semver
|
|
|
|
response = get(
|
|
|
|
"https://gitlab.com/api/v4/projects/20430749/repository/tags"
|
|
|
|
)
|
|
|
|
if response.status_code == 200:
|
2022-07-20 23:39:29 +00:00
|
|
|
remote_version = pkg_version.parse(json.loads(response.text)[0]["name"])
|
2022-07-20 22:53:31 +00:00
|
|
|
|
|
|
|
# Get local version data from the file and parse the semver
|
2022-07-20 23:39:29 +00:00
|
|
|
local_version = pkg_version.parse(self.get_version_string())
|
2022-07-20 22:53:31 +00:00
|
|
|
|
|
|
|
if remote_version > local_version:
|
|
|
|
return remote_version
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
logger.error(f"Unable to check for new crafty version! \n{e}")
|
|
|
|
return False
|
|
|
|
|
2022-08-31 18:04:04 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_latest_bedrock_url():
|
|
|
|
"""
|
|
|
|
Get latest bedrock executable url \n\n
|
|
|
|
returns url if successful, False if not
|
|
|
|
"""
|
|
|
|
url = "https://minecraft.net/en-us/download/server/bedrock/"
|
|
|
|
headers = {
|
|
|
|
"Accept-Encoding": "identity",
|
|
|
|
"Accept-Language": "en",
|
|
|
|
"User-Agent": (
|
|
|
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
|
|
|
|
"AppleWebKit/537.36 (KHTML, like Gecko) "
|
|
|
|
"Chrome/104.0.0.0 Safari/537.36"
|
|
|
|
),
|
|
|
|
}
|
|
|
|
target_win = 'https://minecraft.azureedge.net/bin-win/[^"]*'
|
|
|
|
target_linux = 'https://minecraft.azureedge.net/bin-linux/[^"]*'
|
|
|
|
|
|
|
|
try:
|
|
|
|
# Get minecraft server download page
|
|
|
|
# (hopefully the don't change the structure)
|
|
|
|
download_page = get(url, headers=headers)
|
|
|
|
|
|
|
|
# Search for our string targets
|
|
|
|
win_download_url = re.search(target_win, download_page.text).group(0)
|
|
|
|
linux_download_url = re.search(target_linux, download_page.text).group(0)
|
|
|
|
|
|
|
|
if os.name == "nt":
|
|
|
|
return win_download_url
|
|
|
|
|
|
|
|
return linux_download_url
|
|
|
|
except Exception as e:
|
|
|
|
logger.error(f"Unable to resolve remote bedrock download url! \n{e}")
|
|
|
|
return False
|
|
|
|
|
2022-06-20 17:05:39 +00:00
|
|
|
@staticmethod
|
|
|
|
def find_java_installs():
|
2022-06-20 22:44:33 +00:00
|
|
|
# If we're windows return oracle java versions,
|
|
|
|
# otherwise java vers need to be manual.
|
|
|
|
if os.name == "nt":
|
|
|
|
# Adapted from LeeKamentsky >>>
|
|
|
|
# https://github.com/LeeKamentsky/python-javabridge/blob/master/javabridge/locate.py
|
|
|
|
jdk_key_paths = (
|
|
|
|
"SOFTWARE\\JavaSoft\\JDK",
|
|
|
|
"SOFTWARE\\JavaSoft\\Java Development Kit",
|
|
|
|
)
|
|
|
|
java_paths = []
|
|
|
|
for jdk_key_path in jdk_key_paths:
|
|
|
|
try:
|
|
|
|
with suppress(OSError), winreg.OpenKey(
|
|
|
|
winreg.HKEY_LOCAL_MACHINE, jdk_key_path
|
|
|
|
) as kjdk:
|
|
|
|
for i in itertools.count():
|
2022-07-20 23:39:29 +00:00
|
|
|
version = winreg.EnumKey(kjdk, i)
|
2022-06-20 22:44:33 +00:00
|
|
|
kjdk_current = winreg.OpenKey(
|
|
|
|
winreg.HKEY_LOCAL_MACHINE,
|
|
|
|
jdk_key_path,
|
|
|
|
)
|
|
|
|
kjdk_current = winreg.OpenKey(
|
|
|
|
winreg.HKEY_LOCAL_MACHINE,
|
2022-07-20 23:39:29 +00:00
|
|
|
jdk_key_path + "\\" + version,
|
2022-06-20 22:44:33 +00:00
|
|
|
)
|
|
|
|
kjdk_current_values = dict( # pylint: disable=consider-using-dict-comprehension
|
|
|
|
[
|
|
|
|
winreg.EnumValue(kjdk_current, i)[:2]
|
|
|
|
for i in range(winreg.QueryInfoKey(kjdk_current)[1])
|
|
|
|
]
|
|
|
|
)
|
|
|
|
java_paths.append(kjdk_current_values["JavaHome"])
|
|
|
|
except OSError as e:
|
|
|
|
if e.errno == 2:
|
|
|
|
continue
|
|
|
|
raise
|
|
|
|
return java_paths
|
|
|
|
|
|
|
|
# If we get here we're linux so we will use 'update-alternatives'
|
|
|
|
# (If distro does not have update-alternatives then manual input.)
|
2022-06-24 01:28:05 +00:00
|
|
|
|
|
|
|
# Sometimes u-a will be in /sbin on some distros (which is annoying.)
|
|
|
|
ua_path = "/usr/bin/update-alternatives"
|
|
|
|
if not os.path.exists(ua_path):
|
|
|
|
logger.warning("update-alternatives not found! Trying /sbin")
|
|
|
|
ua_path = "/usr/sbin/update-alternatives"
|
|
|
|
|
2022-06-20 17:05:39 +00:00
|
|
|
try:
|
|
|
|
paths = subprocess.check_output(
|
2022-06-24 01:28:05 +00:00
|
|
|
[ua_path, "--list", "java"], encoding="utf8"
|
2022-06-20 17:05:39 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
if re.match("^(/[^/ ]*)+/?$", paths):
|
|
|
|
return paths.split("\n")
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
logger.error(f"Java Detect Error: {e}")
|
2022-06-24 01:28:05 +00:00
|
|
|
return []
|
2022-06-20 17:05:39 +00:00
|
|
|
|
2022-04-11 05:23:55 +00:00
|
|
|
@staticmethod
|
2022-05-05 11:02:23 +00:00
|
|
|
def float_to_string(gbs: float):
|
2021-01-19 14:17:29 +00:00
|
|
|
s = str(float(gbs) * 1000).rstrip("0").rstrip(".")
|
|
|
|
return s
|
|
|
|
|
2022-04-11 05:23:55 +00:00
|
|
|
@staticmethod
|
|
|
|
def check_file_perms(path):
|
2020-12-12 19:35:41 +00:00
|
|
|
try:
|
2022-06-17 22:27:55 +00:00
|
|
|
with open(path, "r", encoding="utf-8"):
|
|
|
|
pass
|
2022-01-26 01:45:30 +00:00
|
|
|
logger.info(f"{path} is readable")
|
2020-12-12 19:35:41 +00:00
|
|
|
return True
|
|
|
|
except PermissionError:
|
|
|
|
return False
|
|
|
|
|
2022-04-11 05:23:55 +00:00
|
|
|
@staticmethod
|
|
|
|
def is_file_older_than_x_days(file, days=1):
|
|
|
|
if Helpers.check_file_exists(file):
|
2020-08-23 22:43:28 +00:00
|
|
|
file_time = os.path.getmtime(file)
|
|
|
|
# Check against 24 hours
|
2022-06-14 12:40:57 +00:00
|
|
|
return (time.time() - file_time) / 3600 > 24 * days
|
2022-01-26 01:45:30 +00:00
|
|
|
logger.error(f"{file} does not exist")
|
2020-12-19 13:44:04 +00:00
|
|
|
return True
|
2020-08-23 22:43:28 +00:00
|
|
|
|
2021-11-28 02:52:49 +00:00
|
|
|
def get_servers_root_dir(self):
|
|
|
|
return self.servers_dir
|
|
|
|
|
2022-06-15 02:33:02 +00:00
|
|
|
@staticmethod
|
|
|
|
def which_java():
|
2022-06-15 03:11:40 +00:00
|
|
|
# Adapted from LeeKamentsky >>>
|
|
|
|
# https://github.com/LeeKamentsky/python-javabridge/blob/master/javabridge/locate.py
|
2022-06-15 02:33:02 +00:00
|
|
|
jdk_key_paths = (
|
|
|
|
"SOFTWARE\\JavaSoft\\JDK",
|
|
|
|
"SOFTWARE\\JavaSoft\\Java Development Kit",
|
|
|
|
)
|
|
|
|
for jdk_key_path in jdk_key_paths:
|
|
|
|
try:
|
|
|
|
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, jdk_key_path) as kjdk:
|
2022-06-15 03:52:19 +00:00
|
|
|
kjdk_values = (
|
|
|
|
dict( # pylint: disable=consider-using-dict-comprehension
|
|
|
|
[
|
|
|
|
winreg.EnumValue(kjdk, i)[:2]
|
|
|
|
for i in range(winreg.QueryInfoKey(kjdk)[1])
|
|
|
|
]
|
|
|
|
)
|
2022-06-15 02:33:02 +00:00
|
|
|
)
|
|
|
|
current_version = kjdk_values["CurrentVersion"]
|
|
|
|
kjdk_current = winreg.OpenKey(
|
|
|
|
winreg.HKEY_LOCAL_MACHINE, jdk_key_path + "\\" + current_version
|
|
|
|
)
|
2022-06-15 03:52:19 +00:00
|
|
|
kjdk_current_values = (
|
|
|
|
dict( # pylint: disable=consider-using-dict-comprehension
|
|
|
|
[
|
|
|
|
winreg.EnumValue(kjdk_current, i)[:2]
|
|
|
|
for i in range(winreg.QueryInfoKey(kjdk_current)[1])
|
|
|
|
]
|
|
|
|
)
|
2022-06-15 02:33:02 +00:00
|
|
|
)
|
|
|
|
return kjdk_current_values["JavaHome"]
|
2022-06-15 04:42:29 +00:00
|
|
|
except OSError as e:
|
2022-06-15 02:33:02 +00:00
|
|
|
if e.errno == 2:
|
|
|
|
continue
|
2022-06-15 03:15:46 +00:00
|
|
|
raise
|
2022-06-15 02:33:02 +00:00
|
|
|
|
2021-09-13 17:10:34 +00:00
|
|
|
@staticmethod
|
|
|
|
def check_internet():
|
|
|
|
try:
|
2023-01-03 18:14:10 +00:00
|
|
|
requests.get("https://ntp.org", timeout=1)
|
2021-09-13 17:10:34 +00:00
|
|
|
return True
|
2022-01-26 01:45:30 +00:00
|
|
|
except Exception:
|
2021-09-13 17:10:34 +00:00
|
|
|
return False
|
2021-12-21 22:33:59 +00:00
|
|
|
|
2021-09-13 17:10:34 +00:00
|
|
|
@staticmethod
|
|
|
|
def check_port(server_port):
|
2022-01-08 23:03:45 +00:00
|
|
|
try:
|
2022-03-23 02:50:12 +00:00
|
|
|
ip = get("https://api.ipify.org").content.decode("utf8")
|
2022-01-08 23:03:45 +00:00
|
|
|
except:
|
2022-03-23 02:50:12 +00:00
|
|
|
ip = "google.com"
|
2021-12-21 22:39:24 +00:00
|
|
|
a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
2022-01-08 23:03:45 +00:00
|
|
|
a_socket.settimeout(20.0)
|
|
|
|
|
|
|
|
location = (ip, server_port)
|
|
|
|
result_of_check = a_socket.connect_ex(location)
|
2021-12-21 22:39:24 +00:00
|
|
|
|
2022-01-08 23:03:45 +00:00
|
|
|
a_socket.close()
|
|
|
|
|
2022-06-14 12:40:57 +00:00
|
|
|
return result_of_check == 0
|
2022-01-08 23:03:45 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def check_server_conn(server_port):
|
|
|
|
a_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
|
|
a_socket.settimeout(10.0)
|
2022-03-23 02:50:12 +00:00
|
|
|
ip = "127.0.0.1"
|
2021-12-21 22:39:24 +00:00
|
|
|
|
|
|
|
location = (ip, server_port)
|
|
|
|
result_of_check = a_socket.connect_ex(location)
|
2022-01-08 23:03:45 +00:00
|
|
|
a_socket.close()
|
2021-12-21 22:39:24 +00:00
|
|
|
|
2022-06-14 12:40:57 +00:00
|
|
|
return result_of_check == 0
|
2021-09-13 17:10:34 +00:00
|
|
|
|
2021-09-25 19:29:03 +00:00
|
|
|
@staticmethod
|
|
|
|
def cmdparse(cmd_in):
|
|
|
|
# Parse a string into arguments
|
2022-03-23 02:50:12 +00:00
|
|
|
cmd_out = [] # "argv" output array
|
2022-04-14 02:10:25 +00:00
|
|
|
cmd_index = (
|
|
|
|
-1
|
|
|
|
) # command index - pointer to the argument we're building in cmd_out
|
|
|
|
new_param = True # whether we're creating a new argument/parameter
|
2021-09-25 19:29:03 +00:00
|
|
|
esc = False # whether an escape character was encountered
|
2022-04-14 02:10:25 +00:00
|
|
|
quote_char = None # if we're dealing with a quote, save the quote type here.
|
2022-03-23 06:06:13 +00:00
|
|
|
# Nested quotes to be dealt with by the command
|
2022-04-14 02:10:25 +00:00
|
|
|
for char in cmd_in: # for character in string
|
|
|
|
if (
|
|
|
|
new_param
|
|
|
|
): # if set, begin a new argument and increment the command index.
|
2022-03-23 06:06:13 +00:00
|
|
|
# Continue the loop.
|
2022-04-14 02:10:25 +00:00
|
|
|
if char == " ":
|
2021-09-25 19:29:03 +00:00
|
|
|
continue
|
2022-06-14 12:40:57 +00:00
|
|
|
cmd_index += 1
|
|
|
|
cmd_out.append("")
|
|
|
|
new_param = False
|
2022-03-23 06:06:13 +00:00
|
|
|
if esc: # if we encountered an escape character on the last loop,
|
|
|
|
# append this char regardless of what it is
|
2022-04-14 02:10:25 +00:00
|
|
|
if char not in Helpers.allowed_quotes:
|
|
|
|
cmd_out[cmd_index] += "\\"
|
|
|
|
cmd_out[cmd_index] += char
|
2021-09-25 19:29:03 +00:00
|
|
|
esc = False
|
|
|
|
else:
|
2022-04-14 02:10:25 +00:00
|
|
|
if char == "\\": # if the current character is an escape character,
|
2022-03-23 06:06:13 +00:00
|
|
|
# set the esc flag and continue to next loop
|
2021-09-25 19:29:03 +00:00
|
|
|
esc = True
|
2022-03-23 02:50:12 +00:00
|
|
|
elif (
|
2022-04-14 02:10:25 +00:00
|
|
|
char == " " and quote_char is None
|
2022-03-23 02:50:12 +00:00
|
|
|
): # if we encounter a space and are not dealing with a quote,
|
|
|
|
# set the new argument flag and continue to next loop
|
2022-04-14 02:10:25 +00:00
|
|
|
new_param = True
|
2022-03-23 02:50:12 +00:00
|
|
|
elif (
|
2022-04-14 02:10:25 +00:00
|
|
|
char == quote_char
|
2022-03-23 06:06:13 +00:00
|
|
|
): # if we encounter the character that matches our start quote,
|
|
|
|
# end the quote and continue to next loop
|
2022-04-14 02:10:25 +00:00
|
|
|
quote_char = None
|
|
|
|
elif quote_char is None and (
|
|
|
|
char in Helpers.allowed_quotes
|
2022-03-23 06:06:13 +00:00
|
|
|
): # 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
|
2022-04-14 02:10:25 +00:00
|
|
|
quote_char = char
|
2022-03-23 02:50:12 +00:00
|
|
|
else: # else, just store the character in the current arg
|
2022-04-14 02:10:25 +00:00
|
|
|
cmd_out[cmd_index] += char
|
2021-09-25 19:29:03 +00:00
|
|
|
return cmd_out
|
2021-09-13 17:10:34 +00:00
|
|
|
|
2020-08-28 18:38:42 +00:00
|
|
|
def get_setting(self, key, default_return=False):
|
2020-08-12 00:36:09 +00:00
|
|
|
try:
|
2022-03-23 02:50:12 +00:00
|
|
|
with open(self.settings_file, "r", encoding="utf-8") as f:
|
2020-08-27 22:30:56 +00:00
|
|
|
data = json.load(f)
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2020-08-27 22:30:56 +00:00
|
|
|
if key in data.keys():
|
|
|
|
return data.get(key)
|
|
|
|
|
2022-05-25 13:21:34 +00:00
|
|
|
logger.error(f'Config File Error: Setting "{key}" does not exist')
|
|
|
|
Console.error(f'Config File Error: Setting "{key}" does not exist')
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
except Exception as e:
|
2022-03-23 02:50:12 +00:00
|
|
|
logger.critical(
|
|
|
|
f"Config File Error: Unable to read {self.settings_file} due to {e}"
|
|
|
|
)
|
2022-04-12 01:34:46 +00:00
|
|
|
Console.critical(
|
2022-03-23 02:50:12 +00:00
|
|
|
f"Config File Error: Unable to read {self.settings_file} due to {e}"
|
|
|
|
)
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2020-08-28 18:38:42 +00:00
|
|
|
return default_return
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-12-14 19:54:52 +00:00
|
|
|
@staticmethod
|
|
|
|
def is_subdir(server_path, root_dir):
|
|
|
|
server_path = os.path.realpath(server_path)
|
|
|
|
root_dir = os.path.realpath(root_dir)
|
|
|
|
|
|
|
|
relative = os.path.relpath(server_path, root_dir)
|
|
|
|
|
|
|
|
if relative.startswith(os.pardir):
|
|
|
|
return False
|
2022-12-16 23:47:36 +00:00
|
|
|
return True
|
2022-12-14 19:54:52 +00:00
|
|
|
|
2022-05-25 13:21:34 +00:00
|
|
|
def set_setting(self, key, new_value):
|
2022-04-10 19:39:31 +00:00
|
|
|
try:
|
|
|
|
with open(self.settings_file, "r", encoding="utf-8") as f:
|
|
|
|
data = json.load(f)
|
|
|
|
|
|
|
|
if key in data.keys():
|
|
|
|
data[key] = new_value
|
2022-05-25 13:21:34 +00:00
|
|
|
with open(self.settings_file, "w", encoding="utf-8") as f:
|
|
|
|
json.dump(data, f, indent=2)
|
|
|
|
return True
|
2022-04-10 19:39:31 +00:00
|
|
|
|
2022-05-25 13:21:34 +00:00
|
|
|
logger.error(f'Config File Error: Setting "{key}" does not exist')
|
|
|
|
Console.error(f'Config File Error: Setting "{key}" does not exist')
|
2022-04-10 19:39:31 +00:00
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
logger.critical(
|
|
|
|
f"Config File Error: Unable to read {self.settings_file} due to {e}"
|
|
|
|
)
|
2022-04-12 01:34:46 +00:00
|
|
|
Console.critical(
|
2022-04-10 19:39:31 +00:00
|
|
|
f"Config File Error: Unable to read {self.settings_file} due to {e}"
|
|
|
|
)
|
2022-05-25 13:21:34 +00:00
|
|
|
return False
|
2022-04-10 19:39:31 +00:00
|
|
|
|
2022-09-27 01:23:47 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_themes():
|
|
|
|
return ["default", "dark", "light", "ronald"]
|
|
|
|
|
2022-04-11 05:23:55 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_local_ip():
|
2020-08-12 00:36:09 +00:00
|
|
|
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
|
|
try:
|
|
|
|
# doesn't even have to be reachable
|
2022-03-23 02:50:12 +00:00
|
|
|
s.connect(("10.255.255.255", 1))
|
2022-04-14 02:10:25 +00:00
|
|
|
ip = s.getsockname()[0]
|
2020-08-12 00:36:09 +00:00
|
|
|
except Exception:
|
2022-04-14 02:10:25 +00:00
|
|
|
ip = "127.0.0.1"
|
2020-08-12 00:36:09 +00:00
|
|
|
finally:
|
|
|
|
s.close()
|
2022-04-14 02:10:25 +00:00
|
|
|
return ip
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
def get_version(self):
|
|
|
|
version_data = {}
|
|
|
|
try:
|
2022-03-23 02:50:12 +00:00
|
|
|
with open(
|
|
|
|
os.path.join(self.config_dir, "version.json"), "r", encoding="utf-8"
|
|
|
|
) as f:
|
2020-08-12 00:36:09 +00:00
|
|
|
version_data = json.load(f)
|
|
|
|
|
|
|
|
except Exception as e:
|
2022-04-12 01:34:46 +00:00
|
|
|
Console.critical(f"Unable to get version data! \n{e}")
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
return version_data
|
|
|
|
|
2020-09-23 01:42:41 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_announcements():
|
2022-03-23 02:50:12 +00:00
|
|
|
data = (
|
2022-03-23 06:06:13 +00:00
|
|
|
'[{"id":"1","date":"Unknown",'
|
|
|
|
'"title":"Error getting Announcements",'
|
|
|
|
'"desc":"Error getting Announcements","link":""}]'
|
2022-03-23 02:50:12 +00:00
|
|
|
)
|
2020-09-23 01:42:41 +00:00
|
|
|
|
2022-05-05 00:32:09 +00:00
|
|
|
try:
|
|
|
|
response = requests.get("https://craftycontrol.com/notify.json", timeout=2)
|
|
|
|
data = json.loads(response.content)
|
|
|
|
except Exception as e:
|
|
|
|
logger.error(f"Failed to fetch notifications with error: {e}")
|
2020-09-23 01:42:41 +00:00
|
|
|
|
|
|
|
return data
|
|
|
|
|
2020-08-17 02:47:53 +00:00
|
|
|
def get_version_string(self):
|
|
|
|
version_data = self.get_version()
|
2022-03-23 02:50:12 +00:00
|
|
|
major = version_data.get("major", "?")
|
|
|
|
minor = version_data.get("minor", "?")
|
|
|
|
sub = version_data.get("sub", "?")
|
2022-01-26 01:45:30 +00:00
|
|
|
|
2020-08-17 02:47:53 +00:00
|
|
|
# set some defaults if we don't get version_data from our helper
|
2022-10-08 17:34:38 +00:00
|
|
|
version = f"{major}.{minor}.{sub}"
|
2022-07-20 23:39:29 +00:00
|
|
|
return str(version)
|
2020-08-17 02:47:53 +00:00
|
|
|
|
2020-08-13 01:33:36 +00:00
|
|
|
def encode_pass(self, password):
|
|
|
|
return self.passhasher.hash(password)
|
|
|
|
|
|
|
|
def verify_pass(self, password, currenthash):
|
|
|
|
try:
|
|
|
|
self.passhasher.verify(currenthash, password)
|
|
|
|
return True
|
|
|
|
except:
|
|
|
|
return False
|
|
|
|
|
2020-09-02 01:30:39 +00:00
|
|
|
def log_colors(self, line):
|
|
|
|
# our regex replacements
|
|
|
|
# note these are in a tuple
|
|
|
|
|
2022-03-23 02:50:12 +00:00
|
|
|
user_keywords = self.get_setting("keywords")
|
2020-09-02 01:30:39 +00:00
|
|
|
|
|
|
|
replacements = [
|
2022-03-23 02:50:12 +00:00
|
|
|
(r"(\[.+?/INFO\])", r'<span class="mc-log-info">\1</span>'),
|
|
|
|
(r"(\[.+?/WARN\])", r'<span class="mc-log-warn">\1</span>'),
|
|
|
|
(r"(\[.+?/ERROR\])", r'<span class="mc-log-error">\1</span>'),
|
|
|
|
(r"(\[.+?/FATAL\])", r'<span class="mc-log-fatal">\1</span>'),
|
|
|
|
(
|
|
|
|
r"(\w+?\[/\d+?\.\d+?\.\d+?\.\d+?\:\d+?\])",
|
|
|
|
r'<span class="mc-log-keyword">\1</span>',
|
|
|
|
),
|
|
|
|
(r"\[(\d\d:\d\d:\d\d)\]", r'<span class="mc-log-time">[\1]</span>'),
|
|
|
|
(r"(\[.+? INFO\])", r'<span class="mc-log-info">\1</span>'),
|
|
|
|
(r"(\[.+? WARN\])", r'<span class="mc-log-warn">\1</span>'),
|
|
|
|
(r"(\[.+? ERROR\])", r'<span class="mc-log-error">\1</span>'),
|
|
|
|
(r"(\[.+? FATAL\])", r'<span class="mc-log-fatal">\1</span>'),
|
2020-09-02 01:30:39 +00:00
|
|
|
]
|
|
|
|
|
|
|
|
# highlight users keywords
|
|
|
|
for keyword in user_keywords:
|
2022-01-26 01:45:30 +00:00
|
|
|
# pylint: disable=consider-using-f-string
|
2022-03-23 02:50:12 +00:00
|
|
|
search_replace = (
|
|
|
|
r"({})".format(keyword),
|
|
|
|
r'<span class="mc-log-keyword">\1</span>',
|
|
|
|
)
|
2020-09-02 01:30:39 +00:00
|
|
|
replacements.append(search_replace)
|
|
|
|
|
|
|
|
for old, new in replacements:
|
|
|
|
line = re.sub(old, new, line, flags=re.IGNORECASE)
|
|
|
|
|
|
|
|
return line
|
|
|
|
|
2022-04-11 05:23:55 +00:00
|
|
|
@staticmethod
|
|
|
|
def validate_traversal(base_path, filename):
|
2022-03-23 02:50:12 +00:00
|
|
|
logger.debug(f'Validating traversal ("{base_path}", "{filename}")')
|
2021-11-28 02:52:49 +00:00
|
|
|
base = pathlib.Path(base_path).resolve()
|
|
|
|
file = pathlib.Path(filename)
|
|
|
|
fileabs = base.joinpath(file).resolve()
|
2022-04-14 02:10:25 +00:00
|
|
|
common_path = pathlib.Path(os.path.commonpath([base, fileabs]))
|
|
|
|
if base == common_path:
|
2021-11-28 02:52:49 +00:00
|
|
|
return fileabs
|
2022-06-14 12:40:57 +00:00
|
|
|
raise ValueError("Path traversal detected")
|
2021-11-28 02:52:49 +00:00
|
|
|
|
2022-04-11 05:23:55 +00:00
|
|
|
@staticmethod
|
|
|
|
def tail_file(file_name, number_lines=20):
|
|
|
|
if not Helpers.check_file_exists(file_name):
|
2022-01-26 01:45:30 +00:00
|
|
|
logger.warning(f"Unable to find file to tail: {file_name}")
|
|
|
|
return [f"Unable to find file to tail: {file_name}"]
|
2020-09-02 01:30:39 +00:00
|
|
|
|
|
|
|
# length of lines is X char here
|
|
|
|
avg_line_length = 255
|
|
|
|
|
|
|
|
# create our buffer number - number of lines * avg_line_length
|
|
|
|
line_buffer = number_lines * avg_line_length
|
|
|
|
|
|
|
|
# open our file
|
2022-03-23 02:50:12 +00:00
|
|
|
with open(file_name, "r", encoding="utf-8") as f:
|
2020-09-02 01:30:39 +00:00
|
|
|
|
|
|
|
# seek
|
|
|
|
f.seek(0, 2)
|
|
|
|
|
|
|
|
# get file size
|
|
|
|
fsize = f.tell()
|
|
|
|
|
2022-03-23 06:06:13 +00:00
|
|
|
# set pos @ last n chars
|
|
|
|
# (buffer from above = number of lines * avg_line_length)
|
2022-03-23 02:50:12 +00:00
|
|
|
f.seek(max(fsize - line_buffer, 0), 0)
|
2020-09-02 01:30:39 +00:00
|
|
|
|
|
|
|
# read file til the end
|
|
|
|
try:
|
|
|
|
lines = f.readlines()
|
|
|
|
|
|
|
|
except Exception as e:
|
2022-03-23 02:50:12 +00:00
|
|
|
logger.warning(
|
|
|
|
f"Unable to read a line in the file:{file_name} - due to error: {e}"
|
|
|
|
)
|
2020-09-02 01:30:39 +00:00
|
|
|
|
|
|
|
# now we are done getting the lines, let's return it
|
|
|
|
return lines
|
|
|
|
|
2020-08-12 00:36:09 +00:00
|
|
|
@staticmethod
|
|
|
|
def check_writeable(path: str):
|
|
|
|
filename = os.path.join(path, "tempfile.txt")
|
|
|
|
try:
|
2022-06-17 22:27:55 +00:00
|
|
|
with open(filename, "w", encoding="utf-8"):
|
|
|
|
pass
|
2020-08-12 00:36:09 +00:00
|
|
|
os.remove(filename)
|
|
|
|
|
2022-01-26 01:45:30 +00:00
|
|
|
logger.info(f"{filename} is writable")
|
2020-08-12 00:36:09 +00:00
|
|
|
return True
|
|
|
|
|
|
|
|
except Exception as e:
|
2022-01-26 01:45:30 +00:00
|
|
|
logger.critical(f"Unable to write to {path} - Error: {e}")
|
2020-08-12 00:36:09 +00:00
|
|
|
return False
|
|
|
|
|
2022-04-11 05:23:55 +00:00
|
|
|
@staticmethod
|
2022-04-14 02:10:25 +00:00
|
|
|
def check_root():
|
2022-04-11 05:23:55 +00:00
|
|
|
if Helpers.is_os_windows():
|
2022-06-14 12:40:57 +00:00
|
|
|
return ctypes.windll.shell32.IsUserAnAdmin() == 1
|
|
|
|
return os.geteuid() == 0
|
2021-11-29 21:22:46 +00:00
|
|
|
|
2020-08-12 00:36:09 +00:00
|
|
|
def ensure_logging_setup(self):
|
2022-03-23 02:50:12 +00:00
|
|
|
log_file = os.path.join(os.path.curdir, "logs", "commander.log")
|
|
|
|
session_log_file = os.path.join(os.path.curdir, "logs", "session.log")
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
logger.info("Checking app directory writable")
|
|
|
|
|
2022-04-11 05:23:55 +00:00
|
|
|
writeable = Helpers.check_writeable(self.root_dir)
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
# if not writeable, let's bomb out
|
|
|
|
if not writeable:
|
2022-01-26 01:45:30 +00:00
|
|
|
logger.critical(f"Unable to write to {self.root_dir} directory!")
|
2020-08-12 00:36:09 +00:00
|
|
|
sys.exit(1)
|
|
|
|
|
2022-06-24 02:56:31 +00:00
|
|
|
# ensure the log directory is there
|
2020-08-12 00:36:09 +00:00
|
|
|
try:
|
2021-11-23 18:22:15 +00:00
|
|
|
with suppress(FileExistsError):
|
2022-03-23 02:50:12 +00:00
|
|
|
os.makedirs(os.path.join(self.root_dir, "logs"))
|
2020-08-12 00:36:09 +00:00
|
|
|
except Exception as e:
|
2022-04-12 01:34:46 +00:00
|
|
|
Console.error(f"Failed to make logs directory with error: {e} ")
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
# ensure the log file is there
|
|
|
|
try:
|
2022-06-17 22:27:55 +00:00
|
|
|
with open(log_file, "a", encoding="utf-8"):
|
|
|
|
pass
|
2020-08-12 00:36:09 +00:00
|
|
|
except Exception as e:
|
2022-04-12 01:34:46 +00:00
|
|
|
Console.critical(f"Unable to open log file! {e}")
|
2020-08-12 00:36:09 +00:00
|
|
|
sys.exit(1)
|
|
|
|
|
2020-08-13 01:33:36 +00:00
|
|
|
# del any old session.lock file as this is a new session
|
2020-08-12 00:36:09 +00:00
|
|
|
try:
|
2022-06-13 21:16:49 +00:00
|
|
|
with contextlib.suppress(FileNotFoundError):
|
|
|
|
os.remove(session_log_file)
|
2021-11-17 22:23:14 +00:00
|
|
|
except Exception as e:
|
2022-06-13 21:30:28 +00:00
|
|
|
Console.error(f"Deleting logs/session.log failed with error: {e}")
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2020-08-13 14:38:36 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_time_as_string():
|
|
|
|
now = datetime.now()
|
|
|
|
return now.strftime("%m/%d/%Y, %H:%M:%S")
|
2022-03-13 13:26:38 +00:00
|
|
|
|
2022-03-10 04:45:49 +00:00
|
|
|
@staticmethod
|
|
|
|
def calc_percent(source_path, dest_path):
|
2022-03-23 06:06:13 +00:00
|
|
|
# calculates percentable of zip from drive. Not with compression.
|
|
|
|
# (For backups and support logs)
|
2022-03-10 04:45:49 +00:00
|
|
|
source_size = 0
|
2022-03-11 05:19:05 +00:00
|
|
|
files_count = 0
|
2022-03-10 04:45:49 +00:00
|
|
|
for path, _dirs, files in os.walk(source_path):
|
2022-04-14 02:10:25 +00:00
|
|
|
for file in files:
|
|
|
|
full_path = os.path.join(path, file)
|
|
|
|
source_size += os.stat(full_path).st_size
|
2022-03-11 05:19:05 +00:00
|
|
|
files_count += 1
|
2022-04-17 17:00:05 +00:00
|
|
|
try:
|
|
|
|
dest_size = os.path.getsize(str(dest_path))
|
|
|
|
percent = round((dest_size / source_size) * 100, 1)
|
|
|
|
except:
|
|
|
|
percent = 0
|
2022-03-11 05:19:05 +00:00
|
|
|
if percent >= 0:
|
2022-03-23 02:50:12 +00:00
|
|
|
results = {"percent": percent, "total_files": files_count}
|
2022-03-11 05:19:05 +00:00
|
|
|
else:
|
2022-04-17 17:00:05 +00:00
|
|
|
results = {"percent": 0, "total_files": files_count}
|
2022-03-11 05:19:05 +00:00
|
|
|
return results
|
2020-08-13 14:38:36 +00:00
|
|
|
|
2020-08-12 00:36:09 +00:00
|
|
|
@staticmethod
|
|
|
|
def check_file_exists(path: str):
|
2022-03-23 02:50:12 +00:00
|
|
|
logger.debug(f"Looking for path: {path}")
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
if os.path.exists(path) and os.path.isfile(path):
|
2022-03-23 02:50:12 +00:00
|
|
|
logger.debug(f"Found path: {path}")
|
2020-08-12 00:36:09 +00:00
|
|
|
return True
|
2022-06-14 12:40:57 +00:00
|
|
|
return False
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2022-03-23 02:50:12 +00:00
|
|
|
def human_readable_file_size(num: int, suffix="B"):
|
|
|
|
for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
|
2020-08-12 00:36:09 +00:00
|
|
|
if abs(num) < 1024.0:
|
2022-03-23 02:50:12 +00:00
|
|
|
# pylint: disable=consider-using-f-string
|
2020-08-12 00:36:09 +00:00
|
|
|
return "%3.1f%s%s" % (num, unit, suffix)
|
|
|
|
num /= 1024.0
|
2022-01-26 01:45:30 +00:00
|
|
|
# pylint: disable=consider-using-f-string
|
2022-03-23 02:50:12 +00:00
|
|
|
return "%.1f%s%s" % (num, "Y", suffix)
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2021-01-17 17:20:28 +00:00
|
|
|
def check_path_exists(path: str):
|
2021-03-22 04:02:18 +00:00
|
|
|
if not path:
|
|
|
|
return False
|
2022-03-23 02:50:12 +00:00
|
|
|
logger.debug(f"Looking for path: {path}")
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
if os.path.exists(path):
|
2022-03-23 02:50:12 +00:00
|
|
|
logger.debug(f"Found path: {path}")
|
2020-08-12 00:36:09 +00:00
|
|
|
return True
|
2022-06-14 12:40:57 +00:00
|
|
|
return False
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-09-12 19:34:47 +00:00
|
|
|
def get_gravatar_image(self, email):
|
|
|
|
profile_url = "/static/assets/images/faces-clipart/pic-3.png"
|
|
|
|
# http://en.gravatar.com/site/implement/images/#rating
|
|
|
|
if self.get_setting("allow_nsfw_profile_pictures"):
|
|
|
|
rating = "x"
|
|
|
|
else:
|
|
|
|
rating = "g"
|
|
|
|
|
|
|
|
# Get grvatar hash for profile pictures
|
2022-09-20 00:00:15 +00:00
|
|
|
if self.check_internet() and email != "default@example.com" and email:
|
2022-09-12 19:34:47 +00:00
|
|
|
gravatar = libgravatar.Gravatar(libgravatar.sanitize_email(email))
|
|
|
|
url = gravatar.get_image(
|
|
|
|
size=80,
|
|
|
|
default="404",
|
|
|
|
force_default=False,
|
|
|
|
rating=rating,
|
|
|
|
filetype_extension=False,
|
|
|
|
use_ssl=True,
|
|
|
|
) # + "?d=404"
|
|
|
|
try:
|
|
|
|
if requests.head(url).status_code != 404:
|
|
|
|
profile_url = url
|
2022-09-12 19:36:13 +00:00
|
|
|
except Exception as e:
|
|
|
|
logger.debug(f"Could not pull resource from Gravatar with error {e}")
|
2022-09-12 19:34:47 +00:00
|
|
|
|
|
|
|
return profile_url
|
|
|
|
|
2020-08-12 00:36:09 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_file_contents(path: str, lines=100):
|
|
|
|
|
2022-03-23 02:50:12 +00:00
|
|
|
contents = ""
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
if os.path.exists(path) and os.path.isfile(path):
|
|
|
|
try:
|
2022-03-23 02:50:12 +00:00
|
|
|
with open(path, "r", encoding="utf-8") as f:
|
|
|
|
for line in f.readlines()[-lines:]:
|
2020-08-12 00:36:09 +00:00
|
|
|
contents = contents + line
|
|
|
|
|
|
|
|
return contents
|
|
|
|
|
|
|
|
except Exception as e:
|
2022-01-26 01:45:30 +00:00
|
|
|
logger.error(f"Unable to read file: {path}. \n Error: {e}")
|
2020-08-12 00:36:09 +00:00
|
|
|
return False
|
|
|
|
else:
|
2022-03-23 02:50:12 +00:00
|
|
|
logger.error(
|
|
|
|
f"Unable to read file: {path}. File not found, or isn't a file."
|
|
|
|
)
|
2020-08-12 00:36:09 +00:00
|
|
|
return False
|
|
|
|
|
|
|
|
def create_session_file(self, ignore=False):
|
|
|
|
|
|
|
|
if ignore and os.path.exists(self.session_file):
|
|
|
|
os.remove(self.session_file)
|
|
|
|
|
|
|
|
if os.path.exists(self.session_file):
|
|
|
|
|
|
|
|
file_data = self.get_file_contents(self.session_file)
|
|
|
|
try:
|
|
|
|
data = json.loads(file_data)
|
2022-03-23 02:50:12 +00:00
|
|
|
pid = data.get("pid")
|
|
|
|
started = data.get("started")
|
2022-03-02 14:48:03 +00:00
|
|
|
if psutil.pid_exists(pid):
|
2022-04-12 01:34:46 +00:00
|
|
|
Console.critical(
|
2022-03-23 06:06:13 +00:00
|
|
|
f"Another Crafty Controller agent seems to be running..."
|
|
|
|
f"\npid: {pid} \nstarted on: {started}"
|
2022-03-23 02:50:12 +00:00
|
|
|
)
|
2022-03-02 14:48:03 +00:00
|
|
|
logger.critical("Found running crafty process. Exiting.")
|
|
|
|
sys.exit(1)
|
|
|
|
else:
|
2022-03-23 02:50:12 +00:00
|
|
|
logger.info(
|
2022-03-23 06:06:13 +00:00
|
|
|
"No process found for pid. Assuming "
|
|
|
|
"crafty crashed. Deleting stale session.lock"
|
2022-03-23 02:50:12 +00:00
|
|
|
)
|
2022-03-02 14:48:03 +00:00
|
|
|
os.remove(self.session_file)
|
|
|
|
|
2020-08-12 00:36:09 +00:00
|
|
|
except Exception as e:
|
2022-01-26 01:45:30 +00:00
|
|
|
logger.error(f"Failed to locate existing session.lock with error: {e} ")
|
2022-04-12 01:34:46 +00:00
|
|
|
Console.error(
|
2022-03-23 02:50:12 +00:00
|
|
|
f"Failed to locate existing session.lock with error: {e} "
|
|
|
|
)
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-03-02 14:48:03 +00:00
|
|
|
sys.exit(1)
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
pid = os.getpid()
|
|
|
|
now = datetime.now()
|
|
|
|
|
2022-03-23 02:50:12 +00:00
|
|
|
session_data = {"pid": pid, "started": now.strftime("%d-%m-%Y, %H:%M:%S")}
|
|
|
|
with open(self.session_file, "w", encoding="utf-8") as f:
|
2022-06-17 22:30:50 +00:00
|
|
|
json.dump(session_data, f, indent=4)
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-03-23 06:06:13 +00:00
|
|
|
# because this is a recursive function, we will return bytes,
|
|
|
|
# and set human readable later
|
2022-04-11 05:23:55 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_dir_size(path: str):
|
2020-08-12 00:36:09 +00:00
|
|
|
total = 0
|
|
|
|
for entry in os.scandir(path):
|
|
|
|
if entry.is_dir(follow_symlinks=False):
|
2022-04-11 05:23:55 +00:00
|
|
|
total += Helpers.get_dir_size(entry.path)
|
2020-08-12 00:36:09 +00:00
|
|
|
else:
|
|
|
|
total += entry.stat(follow_symlinks=False).st_size
|
|
|
|
return total
|
|
|
|
|
2021-03-22 04:02:18 +00:00
|
|
|
@staticmethod
|
|
|
|
def list_dir_by_date(path: str, reverse=False):
|
2022-03-23 02:50:12 +00:00
|
|
|
return [
|
|
|
|
str(p)
|
|
|
|
for p in sorted(
|
|
|
|
pathlib.Path(path).iterdir(), key=os.path.getmtime, reverse=reverse
|
|
|
|
)
|
|
|
|
]
|
2021-03-22 04:02:18 +00:00
|
|
|
|
2022-04-11 05:23:55 +00:00
|
|
|
@staticmethod
|
|
|
|
def get_human_readable_files_sizes(paths: list):
|
2021-03-22 04:02:18 +00:00
|
|
|
sizes = []
|
|
|
|
for p in paths:
|
2022-03-23 02:50:12 +00:00
|
|
|
sizes.append(
|
2022-04-11 10:08:36 +00:00
|
|
|
{
|
|
|
|
"path": p,
|
|
|
|
"size": Helpers.human_readable_file_size(os.stat(p).st_size),
|
|
|
|
}
|
2022-03-23 02:50:12 +00:00
|
|
|
)
|
2021-03-22 04:02:18 +00:00
|
|
|
return sizes
|
|
|
|
|
2020-08-12 00:36:09 +00:00
|
|
|
@staticmethod
|
2022-01-26 01:45:30 +00:00
|
|
|
def base64_encode_string(fun_str: str):
|
2022-03-23 02:50:12 +00:00
|
|
|
s_bytes = str(fun_str).encode("utf-8")
|
2020-08-12 00:36:09 +00:00
|
|
|
b64_bytes = base64.encodebytes(s_bytes)
|
2022-03-23 02:50:12 +00:00
|
|
|
return b64_bytes.decode("utf-8")
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
@staticmethod
|
2022-01-26 01:45:30 +00:00
|
|
|
def base64_decode_string(fun_str: str):
|
2022-03-23 02:50:12 +00:00
|
|
|
s_bytes = str(fun_str).encode("utf-8")
|
2020-08-12 00:36:09 +00:00
|
|
|
b64_bytes = base64.decodebytes(s_bytes)
|
|
|
|
return b64_bytes.decode("utf-8")
|
|
|
|
|
2022-04-11 05:23:55 +00:00
|
|
|
@staticmethod
|
|
|
|
def create_uuid():
|
2020-08-23 22:43:28 +00:00
|
|
|
return str(uuid.uuid4())
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-04-11 05:23:55 +00:00
|
|
|
@staticmethod
|
|
|
|
def ensure_dir_exists(path):
|
2020-08-12 00:36:09 +00:00
|
|
|
"""
|
|
|
|
ensures a directory exists
|
|
|
|
|
2022-03-23 06:06:13 +00:00
|
|
|
Checks for the existence of a directory, if the directory isn't there,
|
|
|
|
this function creates the directory
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
Args:
|
|
|
|
path (string): the path you are checking for
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
try:
|
|
|
|
os.makedirs(path)
|
2022-01-26 01:45:30 +00:00
|
|
|
logger.debug(f"Created Directory : {path}")
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
# directory already exists - non-blocking error
|
|
|
|
except FileExistsError:
|
|
|
|
pass
|
2022-06-01 19:11:37 +00:00
|
|
|
except PermissionError as e:
|
|
|
|
logger.critical(f"Check generated exception due to permssion error: {e}")
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
def create_self_signed_cert(self, cert_dir=None):
|
|
|
|
|
|
|
|
if cert_dir is None:
|
2022-03-15 18:47:49 +00:00
|
|
|
cert_dir = os.path.join(self.config_dir, "web", "certs")
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
# create a directory if needed
|
2022-04-11 05:23:55 +00:00
|
|
|
Helpers.ensure_dir_exists(cert_dir)
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-03-15 18:47:49 +00:00
|
|
|
cert_file = os.path.join(cert_dir, "commander.cert.pem")
|
|
|
|
key_file = os.path.join(cert_dir, "commander.key.pem")
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-01-26 01:45:30 +00:00
|
|
|
logger.info(f"SSL Cert File is set to: {cert_file}")
|
|
|
|
logger.info(f"SSL Key File is set to: {key_file}")
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
# don't create new files if we already have them.
|
2022-04-11 05:23:55 +00:00
|
|
|
if Helpers.check_file_exists(cert_file) and Helpers.check_file_exists(key_file):
|
2022-03-15 18:47:49 +00:00
|
|
|
logger.info("Cert and Key files already exists, not creating them.")
|
2020-08-12 00:36:09 +00:00
|
|
|
return True
|
|
|
|
|
2022-04-12 01:34:46 +00:00
|
|
|
Console.info("Generating a self signed SSL")
|
2020-08-12 00:36:09 +00:00
|
|
|
logger.info("Generating a self signed SSL")
|
|
|
|
|
|
|
|
# create a key pair
|
|
|
|
logger.info("Generating a key pair. This might take a moment.")
|
2022-04-12 01:34:46 +00:00
|
|
|
Console.info("Generating a key pair. This might take a moment.")
|
2020-08-12 00:36:09 +00:00
|
|
|
k = crypto.PKey()
|
|
|
|
k.generate_key(crypto.TYPE_RSA, 4096)
|
|
|
|
|
|
|
|
# create a self-signed cert
|
|
|
|
cert = crypto.X509()
|
|
|
|
cert.get_subject().C = "US"
|
2022-06-03 13:05:26 +00:00
|
|
|
cert.get_subject().ST = "Michigan"
|
|
|
|
cert.get_subject().L = "Kent County"
|
2020-08-12 00:36:09 +00:00
|
|
|
cert.get_subject().O = "Crafty Controller"
|
|
|
|
cert.get_subject().OU = "Server Ops"
|
|
|
|
cert.get_subject().CN = gethostname()
|
2022-03-15 18:47:49 +00:00
|
|
|
alt_names = ",".join(
|
|
|
|
[
|
|
|
|
f"DNS:{socket.gethostname()}",
|
|
|
|
f"DNS:*.{socket.gethostname()}",
|
|
|
|
"DNS:localhost",
|
|
|
|
"DNS:*.localhost",
|
|
|
|
"DNS:127.0.0.1",
|
|
|
|
]
|
|
|
|
).encode()
|
2022-04-14 02:10:25 +00:00
|
|
|
subject_alt_names_ext = crypto.X509Extension(
|
|
|
|
b"subjectAltName", False, alt_names
|
|
|
|
)
|
|
|
|
basic_constraints_ext = crypto.X509Extension(
|
2022-03-15 18:47:49 +00:00
|
|
|
b"basicConstraints", True, b"CA:false"
|
|
|
|
)
|
2022-04-14 02:10:25 +00:00
|
|
|
cert.add_extensions([subject_alt_names_ext, basic_constraints_ext])
|
2022-06-03 13:05:26 +00:00
|
|
|
cert.set_serial_number(secrets.randbelow(254) + 1)
|
2020-08-12 00:36:09 +00:00
|
|
|
cert.gmtime_adj_notBefore(0)
|
2020-09-02 01:30:39 +00:00
|
|
|
cert.gmtime_adj_notAfter(365 * 24 * 60 * 60)
|
2020-08-12 00:36:09 +00:00
|
|
|
cert.set_issuer(cert.get_subject())
|
|
|
|
cert.set_pubkey(k)
|
2022-03-14 19:30:24 +00:00
|
|
|
cert.set_version(2)
|
2022-03-15 18:47:49 +00:00
|
|
|
cert.sign(k, "sha256")
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-06-17 22:27:55 +00:00
|
|
|
with open(cert_file, "w", encoding="utf-8") as cert_file_handle:
|
|
|
|
cert_file_handle.write(
|
|
|
|
crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode()
|
|
|
|
)
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2022-06-17 22:27:55 +00:00
|
|
|
with open(key_file, "w", encoding="utf-8") as key_file_handle:
|
|
|
|
key_file_handle.write(
|
|
|
|
crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode()
|
|
|
|
)
|
2020-08-12 00:36:09 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def random_string_generator(size=6, chars=string.ascii_uppercase + string.digits):
|
|
|
|
"""
|
|
|
|
Example Usage
|
|
|
|
random_generator() = G8sjO2
|
|
|
|
random_generator(3, abcdef) = adf
|
|
|
|
"""
|
2022-06-03 13:05:26 +00:00
|
|
|
return "".join(secrets.choice(chars) for x in range(size))
|
2020-08-12 00:36:09 +00:00
|
|
|
|
2020-08-17 02:47:53 +00:00
|
|
|
@staticmethod
|
|
|
|
def is_os_windows():
|
2022-06-14 12:40:57 +00:00
|
|
|
return os.name == "nt"
|
2020-08-13 01:33:36 +00:00
|
|
|
|
2021-11-21 10:52:29 +00:00
|
|
|
@staticmethod
|
|
|
|
def wtol_path(w_path):
|
2022-03-23 02:50:12 +00:00
|
|
|
l_path = w_path.replace("\\", "/")
|
2021-11-21 10:52:29 +00:00
|
|
|
return l_path
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def ltow_path(l_path):
|
2022-03-23 02:50:12 +00:00
|
|
|
w_path = l_path.replace("/", "\\")
|
2021-11-21 10:52:29 +00:00
|
|
|
return w_path
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def get_os_understandable_path(path):
|
|
|
|
return os.path.normpath(path)
|
|
|
|
|
2020-08-19 01:50:24 +00:00
|
|
|
def find_default_password(self):
|
|
|
|
default_file = os.path.join(self.root_dir, "default.json")
|
|
|
|
data = {}
|
|
|
|
|
2022-04-11 05:23:55 +00:00
|
|
|
if Helpers.check_file_exists(default_file):
|
2022-03-23 02:50:12 +00:00
|
|
|
with open(default_file, "r", encoding="utf-8") as f:
|
2020-08-19 01:50:24 +00:00
|
|
|
data = json.load(f)
|
|
|
|
|
2022-04-11 05:23:55 +00:00
|
|
|
del_json = self.get_setting("delete_default_json")
|
2020-08-27 22:30:56 +00:00
|
|
|
|
|
|
|
if del_json:
|
|
|
|
os.remove(default_file)
|
2020-08-19 01:50:24 +00:00
|
|
|
|
|
|
|
return data
|
|
|
|
|
2023-01-27 22:36:23 +00:00
|
|
|
def generate_tree(self, folder, output=""):
|
2022-03-01 21:54:06 +00:00
|
|
|
dir_list = []
|
|
|
|
unsorted_files = []
|
2021-12-21 22:36:49 +00:00
|
|
|
file_list = os.listdir(folder)
|
2022-03-01 21:54:06 +00:00
|
|
|
for item in file_list:
|
|
|
|
if os.path.isdir(os.path.join(folder, item)):
|
|
|
|
dir_list.append(item)
|
2022-06-20 19:26:21 +00:00
|
|
|
elif str(item) != "crafty.sqlite":
|
2022-03-01 21:54:06 +00:00
|
|
|
unsorted_files.append(item)
|
2022-03-23 02:50:12 +00:00
|
|
|
file_list = sorted(dir_list, key=str.casefold) + sorted(
|
|
|
|
unsorted_files, key=str.casefold
|
|
|
|
)
|
2021-12-21 22:36:49 +00:00
|
|
|
for raw_filename in file_list:
|
2021-12-21 21:11:48 +00:00
|
|
|
filename = html.escape(raw_filename)
|
|
|
|
rel = os.path.join(folder, raw_filename)
|
2022-01-26 01:45:30 +00:00
|
|
|
dpath = os.path.join(folder, filename)
|
2021-01-14 22:55:14 +00:00
|
|
|
if os.path.isdir(rel):
|
2023-01-27 22:36:23 +00:00
|
|
|
if filename not in self.ignored_names:
|
2023-01-29 20:18:10 +00:00
|
|
|
output += f"""<li id="{dpath}li" class="tree-item"
|
|
|
|
data-path="{dpath}">
|
2023-01-29 20:13:02 +00:00
|
|
|
\n<div id="{dpath}" data-path="{dpath}" data-name="{filename}"
|
|
|
|
class="tree-caret tree-ctx-item tree-folder">
|
|
|
|
<span id="{dpath}span" class="files-tree-title" data-path="{dpath}"
|
|
|
|
data-name="{filename}" onclick="getDirView(event)">
|
2023-01-09 21:34:12 +00:00
|
|
|
<i style="color: var(--info);" class="far fa-folder"></i>
|
|
|
|
<i style="color: var(--info);" class="far fa-folder-open"></i>
|
|
|
|
{filename}
|
|
|
|
</span>
|
|
|
|
</div><li>
|
|
|
|
\n"""
|
2022-01-08 23:03:45 +00:00
|
|
|
else:
|
2023-01-27 22:36:23 +00:00
|
|
|
if filename not in self.ignored_names:
|
2023-01-29 00:10:27 +00:00
|
|
|
output += f"""<li id="{dpath}li"
|
2022-05-15 17:38:48 +00:00
|
|
|
class="d-block tree-ctx-item tree-file tree-item"
|
2022-01-26 01:45:30 +00:00
|
|
|
data-path="{dpath}"
|
|
|
|
data-name="{filename}"
|
2022-03-23 06:06:13 +00:00
|
|
|
onclick="clickOnFile(event)"><span style="margin-right: 6px;">
|
|
|
|
<i class="far fa-file"></i></span>{filename}</li>"""
|
2022-01-08 23:03:45 +00:00
|
|
|
return output
|
2021-01-17 17:20:28 +00:00
|
|
|
|
2023-01-27 22:36:23 +00:00
|
|
|
def generate_dir(self, folder, output=""):
|
2022-06-20 19:26:21 +00:00
|
|
|
|
2022-03-01 21:54:06 +00:00
|
|
|
dir_list = []
|
|
|
|
unsorted_files = []
|
2022-01-08 23:03:45 +00:00
|
|
|
file_list = os.listdir(folder)
|
2022-03-01 21:54:06 +00:00
|
|
|
for item in file_list:
|
|
|
|
if os.path.isdir(os.path.join(folder, item)):
|
|
|
|
dir_list.append(item)
|
2022-06-20 19:26:21 +00:00
|
|
|
elif str(item) != "crafty.sqlite":
|
2022-03-01 21:54:06 +00:00
|
|
|
unsorted_files.append(item)
|
2022-03-23 02:50:12 +00:00
|
|
|
file_list = sorted(dir_list, key=str.casefold) + sorted(
|
|
|
|
unsorted_files, key=str.casefold
|
|
|
|
)
|
|
|
|
output += f"""<ul class="tree-nested d-block" id="{folder}ul">"""
|
2022-01-08 23:03:45 +00:00
|
|
|
for raw_filename in file_list:
|
|
|
|
filename = html.escape(raw_filename)
|
2022-01-26 01:45:30 +00:00
|
|
|
dpath = os.path.join(folder, filename)
|
2022-01-08 23:03:45 +00:00
|
|
|
rel = os.path.join(folder, raw_filename)
|
|
|
|
if os.path.isdir(rel):
|
2023-01-27 22:36:23 +00:00
|
|
|
if filename not in self.ignored_names:
|
2023-01-29 20:18:10 +00:00
|
|
|
output += f"""<li id="{dpath}li" class="tree-item"
|
|
|
|
data-path="{dpath}">
|
2023-01-29 20:13:02 +00:00
|
|
|
\n<div id="{dpath}" data-path="{dpath}" data-name="{filename}"
|
|
|
|
class="tree-caret tree-ctx-item tree-folder">
|
|
|
|
<span id="{dpath}span" class="files-tree-title" data-path="{dpath}"
|
|
|
|
data-name="{filename}" onclick="getDirView(event)">
|
2023-01-09 21:34:12 +00:00
|
|
|
<i style="color: var(--info);" class="far fa-folder"></i>
|
|
|
|
<i style="color: var(--info);" class="far fa-folder-open"></i>
|
|
|
|
{filename}
|
|
|
|
</span>
|
|
|
|
</div><li>"""
|
2021-01-14 22:55:14 +00:00
|
|
|
else:
|
2023-01-27 22:36:23 +00:00
|
|
|
if filename not in self.ignored_names:
|
2023-01-29 00:10:27 +00:00
|
|
|
output += f"""<li id="{dpath}li"
|
2022-05-15 17:38:48 +00:00
|
|
|
class="d-block tree-ctx-item tree-file tree-item"
|
2022-01-26 01:45:30 +00:00
|
|
|
data-path="{dpath}"
|
|
|
|
data-name="{filename}"
|
2022-03-23 06:06:13 +00:00
|
|
|
onclick="clickOnFile(event)"><span style="margin-right: 6px;">
|
|
|
|
<i class="far fa-file"></i></span>{filename}</li>"""
|
2022-03-23 02:50:12 +00:00
|
|
|
output += "</ul>\n"
|
2021-01-15 12:33:17 +00:00
|
|
|
return output
|
2020-08-19 01:50:24 +00:00
|
|
|
|
2022-01-09 23:04:54 +00:00
|
|
|
@staticmethod
|
2022-01-10 03:21:28 +00:00
|
|
|
def generate_zip_tree(folder, output=""):
|
|
|
|
file_list = os.listdir(folder)
|
|
|
|
file_list = sorted(file_list, key=str.casefold)
|
2022-03-23 02:50:12 +00:00
|
|
|
output += f"""<ul class="tree-nested d-block" id="{folder}ul">"""
|
2022-01-10 03:21:28 +00:00
|
|
|
for raw_filename in file_list:
|
|
|
|
filename = html.escape(raw_filename)
|
|
|
|
rel = os.path.join(folder, raw_filename)
|
2022-01-26 01:45:30 +00:00
|
|
|
dpath = os.path.join(folder, filename)
|
2022-01-10 03:21:28 +00:00
|
|
|
if os.path.isdir(rel):
|
2022-03-23 02:50:12 +00:00
|
|
|
output += f"""<li class="tree-item" data-path="{dpath}">
|
2022-01-26 01:45:30 +00:00
|
|
|
\n<div id="{dpath}" data-path="{dpath}" data-name="{filename}" class="tree-caret tree-ctx-item tree-folder">
|
|
|
|
<input type="radio" name="root_path" value="{dpath}">
|
|
|
|
<span id="{dpath}span" class="files-tree-title" data-path="{dpath}" data-name="{filename}" onclick="getDirView(event)">
|
2022-10-04 17:31:37 +00:00
|
|
|
<i style="color: var(--info);" class="far fa-folder"></i>
|
|
|
|
<i style="color: var(--info);" class="far fa-folder-open"></i>
|
2022-01-26 01:45:30 +00:00
|
|
|
{filename}
|
2022-01-10 03:21:28 +00:00
|
|
|
</span>
|
|
|
|
</input></div><li>
|
2022-03-23 02:50:12 +00:00
|
|
|
\n"""
|
2022-01-10 03:21:28 +00:00
|
|
|
return output
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def generate_zip_dir(folder, output=""):
|
|
|
|
file_list = os.listdir(folder)
|
|
|
|
file_list = sorted(file_list, key=str.casefold)
|
2022-03-23 02:50:12 +00:00
|
|
|
output += f"""<ul class="tree-nested d-block" id="{folder}ul">"""
|
2022-01-10 03:21:28 +00:00
|
|
|
for raw_filename in file_list:
|
|
|
|
filename = html.escape(raw_filename)
|
|
|
|
rel = os.path.join(folder, raw_filename)
|
2022-01-26 01:45:30 +00:00
|
|
|
dpath = os.path.join(folder, filename)
|
2022-01-10 03:21:28 +00:00
|
|
|
if os.path.isdir(rel):
|
2022-03-23 02:50:12 +00:00
|
|
|
output += f"""<li class="tree-item" data-path="{dpath}">
|
2022-01-26 01:45:30 +00:00
|
|
|
\n<div id="{dpath}" data-path="{dpath}" data-name="{filename}" class="tree-caret tree-ctx-item tree-folder">
|
|
|
|
<input type="radio" name="root_path" value="{dpath}">
|
|
|
|
<span id="{dpath}span" class="files-tree-title" data-path="{dpath}" data-name="{filename}" onclick="getDirView(event)">
|
2022-10-04 17:31:37 +00:00
|
|
|
<i style="color: var(--info);" class="far fa-folder"></i>
|
|
|
|
<i style="color: var(--info);" class="far fa-folder-open"></i>
|
2022-01-26 01:45:30 +00:00
|
|
|
{filename}
|
2022-01-10 03:21:28 +00:00
|
|
|
</span>
|
2022-03-23 02:50:12 +00:00
|
|
|
</input></div><li>"""
|
2022-01-10 03:21:28 +00:00
|
|
|
return output
|
|
|
|
|
2022-04-14 02:10:25 +00:00
|
|
|
def unzip_server(self, zip_path, user_id):
|
2022-04-11 05:23:55 +00:00
|
|
|
if Helpers.check_file_perms(zip_path):
|
2022-04-14 02:10:25 +00:00
|
|
|
temp_dir = tempfile.mkdtemp()
|
2022-03-23 02:50:12 +00:00
|
|
|
with zipfile.ZipFile(zip_path, "r") as zip_ref:
|
|
|
|
# extracts archive to temp directory
|
2022-04-14 02:10:25 +00:00
|
|
|
zip_ref.extractall(temp_dir)
|
2022-01-10 03:49:03 +00:00
|
|
|
if user_id:
|
2022-04-11 05:23:55 +00:00
|
|
|
self.websocket_helper.broadcast_user(
|
2022-04-14 02:10:25 +00:00
|
|
|
user_id, "send_temp_path", {"path": temp_dir}
|
2022-03-23 02:50:12 +00:00
|
|
|
)
|
|
|
|
|
2022-04-11 05:23:55 +00:00
|
|
|
def backup_select(self, path, user_id):
|
2022-03-01 01:02:30 +00:00
|
|
|
if user_id:
|
2022-04-11 10:08:36 +00:00
|
|
|
self.websocket_helper.broadcast_user(
|
|
|
|
user_id, "send_temp_path", {"path": path}
|
|
|
|
)
|
2022-01-09 23:04:54 +00:00
|
|
|
|
2022-01-10 05:10:03 +00:00
|
|
|
@staticmethod
|
|
|
|
def unzip_backup_archive(backup_path, zip_name):
|
|
|
|
zip_path = os.path.join(backup_path, zip_name)
|
2022-04-11 05:23:55 +00:00
|
|
|
if Helpers.check_file_perms(zip_path):
|
2022-04-14 02:10:25 +00:00
|
|
|
temp_dir = tempfile.mkdtemp()
|
2022-03-23 02:50:12 +00:00
|
|
|
with zipfile.ZipFile(zip_path, "r") as zip_ref:
|
|
|
|
# extracts archive to temp directory
|
2022-04-14 02:10:25 +00:00
|
|
|
zip_ref.extractall(temp_dir)
|
|
|
|
return temp_dir
|
2022-06-14 12:40:57 +00:00
|
|
|
return False
|
2022-01-10 05:10:03 +00:00
|
|
|
|
2021-01-15 19:59:58 +00:00
|
|
|
@staticmethod
|
2021-08-22 20:31:49 +00:00
|
|
|
def in_path(parent_path, child_path):
|
2022-03-23 06:06:13 +00:00
|
|
|
# Smooth out relative path names, note: if you are concerned about
|
|
|
|
# symbolic links, you should use os.path.realpath too
|
2021-08-22 20:31:49 +00:00
|
|
|
parent_path = os.path.abspath(parent_path)
|
|
|
|
child_path = os.path.abspath(child_path)
|
|
|
|
|
2022-03-23 06:06:13 +00:00
|
|
|
# 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
|
2022-03-23 02:50:12 +00:00
|
|
|
return os.path.commonpath([parent_path]) == os.path.commonpath(
|
|
|
|
[parent_path, child_path]
|
|
|
|
)
|
2021-08-22 20:31:49 +00:00
|
|
|
|
2021-07-25 01:09:39 +00:00
|
|
|
@staticmethod
|
|
|
|
def download_file(executable_url, jar_path):
|
|
|
|
try:
|
2022-04-14 02:10:25 +00:00
|
|
|
response = requests.get(executable_url, timeout=5)
|
2021-07-25 01:09:39 +00:00
|
|
|
except Exception as ex:
|
|
|
|
logger.error("Could not download executable: %s", ex)
|
|
|
|
return False
|
2022-04-14 02:10:25 +00:00
|
|
|
if response.status_code != 200:
|
2021-07-25 01:09:39 +00:00
|
|
|
logger.error("Unable to download file from %s", executable_url)
|
|
|
|
return False
|
|
|
|
|
|
|
|
try:
|
2022-06-17 22:27:55 +00:00
|
|
|
with open(jar_path, "wb") as jar_file:
|
|
|
|
jar_file.write(response.content)
|
2021-07-25 01:09:39 +00:00
|
|
|
except Exception as e:
|
|
|
|
logger.error("Unable to finish executable download. Error: %s", e)
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
2021-08-10 20:17:56 +00:00
|
|
|
@staticmethod
|
|
|
|
def remove_prefix(text, prefix):
|
|
|
|
if text.startswith(prefix):
|
2022-03-23 02:50:12 +00:00
|
|
|
return text[len(prefix) :]
|
2021-08-10 20:17:56 +00:00
|
|
|
return text
|
|
|
|
|
2022-03-05 11:01:36 +00:00
|
|
|
@staticmethod
|
2022-05-18 22:10:06 +00:00
|
|
|
def get_lang_page(text) -> str:
|
|
|
|
splitted = text.split("_")
|
|
|
|
if len(splitted) != 2:
|
|
|
|
return "en"
|
|
|
|
lang, region = splitted
|
2022-03-23 02:50:12 +00:00
|
|
|
if region == "EN":
|
|
|
|
return "en"
|
2022-05-18 22:10:06 +00:00
|
|
|
return lang + "-" + region
|