servii-backend/file_manager.py
Charles Le Maux b6d916bf9a [V2] Final commit, production ready
Signed-off-by: Charles Le Maux <charles.le-maux@epitech.eu>
2024-06-25 22:49:33 +01:00

114 lines
3.8 KiB
Python

import logging
import os
import shutil
import re
import subprocess
supported_versions = ["bukkit", "paper", "spigot"]
def get_all_versions(folder_path="servers/paper"):
return [name for name in os.listdir(folder_path) if os.path.isdir(os.path.join(folder_path, name))]
def version_exists(version, framework="paper") -> bool:
if framework not in supported_versions:
return False
folder_names = get_all_versions("servers/" + framework)
return any(version in name for name in folder_names)
def create_folder(path):
os.makedirs(path, exist_ok=True)
def check_if_exists(path):
return os.path.exists(path)
def delete_non_empty_folder(path):
shutil.rmtree(path)
def copy_folder_contents(source_dir, destination_dir):
if not os.path.exists(destination_dir):
os.makedirs(destination_dir)
for item_name in os.listdir(source_dir):
source_path = os.path.join(source_dir, item_name)
destination_path = os.path.join(destination_dir, item_name)
if os.path.isfile(source_path):
shutil.copy2(source_path, destination_path)
elif os.path.isdir(source_path):
if os.path.exists(destination_path):
for filename in os.listdir(source_path):
file_source_path = os.path.join(source_path, filename)
file_destination_path = os.path.join(destination_path, filename)
if not os.path.exists(file_destination_path):
shutil.copy2(file_source_path, file_destination_path)
else:
shutil.copytree(source_path, destination_path)
def update_server_property(file_path, property_name, new_value):
pattern = rf'^{property_name}=.*$'
with open(file_path, 'r') as file:
content = file.readlines()
for i, line in enumerate(content):
if re.match(pattern, line):
content[i] = f"{property_name}={new_value}\n"
break
else:
raise ValueError(f"Property '{property_name}' not found in the file.")
with open(file_path, 'w') as file:
file.writelines(content)
def reload_nginx() -> bool:
try:
subprocess.run(['nginx', '-s', 'reload'], check=True)
return True
except subprocess.CalledProcessError as e:
return False
def append_stream_config(port, subdomain, config_file_path='/etc/nginx/sites-available/servii.fr'):
os.makedirs(os.path.dirname(config_file_path), exist_ok=True)
with open(config_file_path, 'r') as file:
content = file.read()
new_content = f"""stream {{
server {{
listen 25565;
listen [::]:25565;
server_name {subdomain}.servii.fr;
proxy_pass 127.0.0.1:{port};
}}
}}\n"""
final_content = content + new_content
with open(config_file_path, 'w') as file:
file.write(final_content)
def remove_stream_config(port, subdomain, config_file_path='/etc/nginx/sites-available/servii.fr'):
pattern = (r'stream {{\s*server {{\s*listen 25565;\s*listen \[\(::\]\):'
r'25565;\s*server_name {}.servii\.fr;\s*proxy_pass 127\.0\.0\.1:{};\s*}}}\n'
.format(re.escape(subdomain), port))
with open(config_file_path, 'r') as file:
content = file.read()
cleaned_content = re.sub(pattern, '', content, flags=re.MULTILINE | re.DOTALL)
with open(config_file_path, 'w') as file:
file.write(cleaned_content)
print(f"Stream configuration removed from {config_file_path}")
def log_error(error_type: str, error_message: str):
logging.basicConfig(filename='logs.txt', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(__name__)
logger.error(f'{error_type}: {error_message}')
if __name__ == "__main__":
pass