added permission wrapper

This commit is contained in:
ctih1 2025-07-23 10:19:08 +03:00
parent f7042ed8a7
commit f186e079da
29 changed files with 860 additions and 788 deletions

View file

@ -12,6 +12,7 @@ import importlib.metadata
import logging
import modules.keys as k
from modules.settings import Settings as SettingsManager
settings_manager = SettingsManager()
settings = settings_manager.settings
@ -27,68 +28,75 @@ except ImportError:
psutilavaliable = False
logger.error(k.missing_requests_psutil())
def check_for_model():
if is_package("en_core_web_sm"):
logger.info("Model is installed.")
else:
logger.info("Model is not installed.")
def iscloned():
if os.path.exists(".git"):
return True
else:
logger.error(f"{k.not_cloned()}")
logger.error(f"{k.not_cloned()}")
sys.exit(1)
def get_stdlib_modules():
stdlib_path = pathlib.Path(sysconfig.get_paths()['stdlib'])
stdlib_path = pathlib.Path(sysconfig.get_paths()["stdlib"])
modules = set()
if hasattr(sys, 'builtin_module_names'):
if hasattr(sys, "builtin_module_names"):
modules.update(sys.builtin_module_names)
for file in stdlib_path.glob('*.py'):
if file.stem != '__init__':
for file in stdlib_path.glob("*.py"):
if file.stem != "__init__":
modules.add(file.stem)
for folder in stdlib_path.iterdir():
if folder.is_dir() and (folder / '__init__.py').exists():
if folder.is_dir() and (folder / "__init__.py").exists():
modules.add(folder.name)
for file in stdlib_path.glob('*.*'):
if file.suffix in ('.so', '.pyd'):
for file in stdlib_path.glob("*.*"):
if file.suffix in (".so", ".pyd"):
modules.add(file.stem)
return modules
def check_requirements():
STD_LIB_MODULES = get_stdlib_modules()
PACKAGE_ALIASES = {
"discord": "discord.py",
"better_profanity": "better-profanity",
"dotenv": "python-dotenv",
"pil": "pillow"
"pil": "pillow",
}
parent_dir = os.path.dirname(os.path.abspath(__file__))
requirements_path = os.path.abspath(os.path.join(parent_dir, '..', 'requirements.txt'))
requirements_path = os.path.abspath(
os.path.join(parent_dir, "..", "requirements.txt")
)
if not os.path.exists(requirements_path):
logger.error(f"{k.requirements_not_found(path=requirements_path)}")
return
with open(requirements_path, 'r') as f:
with open(requirements_path, "r") as f:
lines = f.readlines()
requirements = set()
for line in lines:
line = line.strip()
if line and not line.startswith('#'):
base_pkg = line.split('==')[0].lower()
if line and not line.startswith("#"):
base_pkg = line.split("==")[0].lower()
aliased_pkg = PACKAGE_ALIASES.get(base_pkg, base_pkg)
requirements.add(aliased_pkg)
installed_packages = {dist.metadata['Name'].lower() for dist in importlib.metadata.distributions()}
installed_packages = {
dist.metadata["Name"].lower() for dist in importlib.metadata.distributions()
}
missing = []
for req in sorted(requirements):
if req in STD_LIB_MODULES or req == 'modules':
if req in STD_LIB_MODULES or req == "modules":
print(k.std_lib_local_skipped(package=req))
continue
@ -108,6 +116,7 @@ def check_requirements():
else:
logger.info(k.all_requirements_satisfied())
def check_latency():
host = "1.1.1.1"
system = platform.system()
@ -126,10 +135,7 @@ def check_latency():
try:
result = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
)
if result.returncode == 0:
@ -147,25 +153,37 @@ def check_latency():
except Exception as e:
logger.error(k.error_running_ping(error=e))
def check_memory():
if psutilavaliable == False:
return
try:
memory_info = psutil.virtual_memory() # type: ignore
total_memory = memory_info.total / (1024 ** 3)
used_memory = memory_info.used / (1024 ** 3)
free_memory = memory_info.available / (1024 ** 3)
total_memory = memory_info.total / (1024**3)
used_memory = memory_info.used / (1024**3)
free_memory = memory_info.available / (1024**3)
logger.info(k.memory_usage(used=used_memory, total=total_memory, percent=(used_memory / total_memory) * 100))
logger.info(
k.memory_usage(
used=used_memory,
total=total_memory,
percent=(used_memory / total_memory) * 100,
)
)
if used_memory > total_memory * 0.9:
print(f"{YELLOW}{k.memory_above_90(percent=(used_memory / total_memory) * 100)}{RESET}")
print(
f"{YELLOW}{k.memory_above_90(percent=(used_memory / total_memory) * 100)}{RESET}"
)
logger.info(k.total_memory(total=total_memory))
logger.info(k.used_memory(used=used_memory))
if free_memory < 1:
logger.warning(f"{k.low_free_memory(free=free_memory)}")
sys.exit(1)
except ImportError:
logger.error(k.psutil_not_installed()) # todo: translate this into italian and put it in the translations "psutil is not installed. Memory check skipped."
logger.error(
k.psutil_not_installed()
) # todo: translate this into italian and put it in the translations "psutil is not installed. Memory check skipped."
def check_cpu():
if psutilavaliable == False:
@ -180,13 +198,18 @@ def check_cpu():
logger.error(k.really_high_cpu())
sys.exit(1)
def check_memoryjson():
try:
logger.info(k.memory_file(size=os.path.getsize(settings["bot"]["active_memory"]) / (1024 ** 2)))
logger.info(
k.memory_file(
size=os.path.getsize(settings["bot"]["active_memory"]) / (1024**2)
)
)
if os.path.getsize(settings["bot"]["active_memory"]) > 1_073_741_824:
logger.warning(f"{k.memory_file_large()}")
try:
with open(settings["bot"]["active_memory"], 'r', encoding='utf-8') as f:
with open(settings["bot"]["active_memory"], "r", encoding="utf-8") as f:
json.load(f)
except json.JSONDecodeError as e:
logger.error(f"{k.memory_file_corrupted(error=e)}")
@ -199,9 +222,11 @@ def check_memoryjson():
except FileNotFoundError:
logger.info(f"{k.memory_file_not_found()}")
def presskey2skip(timeout):
if os.name == 'nt':
if os.name == "nt":
import msvcrt
start_time = time.time()
while True:
if msvcrt.kbhit():
@ -230,12 +255,16 @@ def presskey2skip(timeout):
time.sleep(0.1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
beta = beta
def start_checks():
if settings["disable_checks"]:
logger.warning(f"{k.checks_disabled()}")
return
logger.info(k.running_prestart_checks())
check_for_model()
iscloned()
@ -250,12 +279,14 @@ def start_checks():
logger.warning(f"{k.env_file_not_found()}")
sys.exit(1)
if beta == True:
logger.warning(f"this build isnt finished yet, some things might not work as expected")
logger.warning(
f"this build isnt finished yet, some things might not work as expected"
)
else:
pass
logger.info(k.continuing_in_seconds(seconds=5))
presskey2skip(timeout=5)
os.system('cls' if os.name == 'nt' else 'clear')
os.system("cls" if os.name == "nt" else "clear")
with open(settings ["splash_text_loc"], "r") as f:
with open(settings["splash_text_loc"], "r") as f:
print("".join(f.readlines()))