Skip to content

Commit

Permalink
Merge pull request #36 from JustKappaMan/pieraknet
Browse files Browse the repository at this point in the history
Refactoring, optimizations, improvements
  • Loading branch information
andiricum2 authored Aug 1, 2023
2 parents 365557a + 478eb21 commit 0f252d3
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 41 deletions.
6 changes: 4 additions & 2 deletions piemc/commands/piemc.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from piemc.handlers.command import Command


@Command
def ping(self):
self.logger.info("Pong!")



@Command
def stop(self):
self.logger.info("Stopping the server...")
self.stop()
self.stop()
5 changes: 4 additions & 1 deletion piemc/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,7 @@
GAMEMODE = "Survival"
LANG = "en"
MOTD = "PieMC Server"
LOG_LEVEL = '' # ONLY FOR DEVELOPERS. Set the desired log level in uppercase (e.g., 'INFO', 'DEBUG', 'WARNING', 'ERROR', 'CRITICAL')

# ONLY FOR DEVELOPERS
# Set the desired log level in uppercase (e.g., "INFO", "DEBUG", "WARNING", "ERROR", "CRITICAL")
LOG_LEVEL = ""
15 changes: 11 additions & 4 deletions piemc/handlers/command.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import importlib
import inspect
import pkgutil

import piemc.commands


registered_commands = {}


def Command(func):
cmd_name = func.__name__.lower()
registered_commands[cmd_name] = func
return func


def handle_command(server, cmd):
cmd = cmd.strip()
if not cmd:
Expand All @@ -18,7 +22,7 @@ def handle_command(server, cmd):

cmd_args = cmd.split()
cmd_name = cmd_args[0].lower()

func = registered_commands.get(cmd_name)
if func is not None:
if inspect.getfullargspec(func).args:
Expand All @@ -27,15 +31,18 @@ def handle_command(server, cmd):
func(server)
else:
print(f"Command '{cmd_name}' not found.")



def initialize_commands(self):
command_classes = []
package_path = piemc.commands.__path__
package_name = piemc.commands.__name__ + '.'
package_name = piemc.commands.__name__ + "."

for importer, modname, ispkg in pkgutil.walk_packages(package_path, package_name):
module = importlib.import_module(modname)
command_classes.extend(cls for name, cls in inspect.getmembers(module, inspect.isclass) if hasattr(cls, 'Command'))
command_classes.extend(
cls for name, cls in inspect.getmembers(module, inspect.isclass) if hasattr(cls, "Command")
)

for command_class in command_classes:
setattr(self, command_class.__name__.lower(), command_class(self.logger, self))
11 changes: 7 additions & 4 deletions piemc/handlers/lang.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,13 @@
# @author PieMC Team
# @link http://www.PieMC-Dev.github.io/

import yaml
from pathlib import Path

import yaml

from piemc import config


class LangHandler:
lang_cache = None

Expand All @@ -33,15 +36,15 @@ def initialize_language():

lang = {}
if lang_file_path.exists():
with lang_file_path.open('r', encoding='utf-8') as lang_file:
with lang_file_path.open("r", encoding="utf-8") as lang_file:
lang = yaml.safe_load(lang_file)
else:
print(f"Language file not found for language: {config.LANG}")

if fallback_lang_file_path.exists():
with fallback_lang_file_path.open('r', encoding='utf-8') as fallback_lang_file:
with fallback_lang_file_path.open("r", encoding="utf-8") as fallback_lang_file:
fallback_lang = yaml.safe_load(fallback_lang_file)
lang = {**fallback_lang, **lang}

LangHandler.lang_cache = lang
return lang
return lang
25 changes: 14 additions & 11 deletions piemc/handlers/logger.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,35 @@
import logging
import os
import logging

import piemc.config


def create_logger(name):
log_level_mapping = {
'DEBUG': logging.DEBUG,
'INFO': logging.INFO,
'WARNING': logging.WARNING,
'ERROR': logging.ERROR,
'CRITICAL': logging.CRITICAL
"DEBUG": logging.DEBUG,
"INFO": logging.INFO,
"WARNING": logging.WARNING,
"ERROR": logging.ERROR,
"CRITICAL": logging.CRITICAL,
}
log_level = log_level_mapping.get(piemc.config.LOG_LEVEL.upper(), logging.INFO)
logger = logging.getLogger(name)
logger.setLevel(log_level)

log_dir = './log'
log_dir = "./log"
os.makedirs(log_dir, exist_ok=True)

log_file = os.path.join(log_dir, name + '.log')
fhandler = logging.FileHandler(log_file, 'w', 'utf-8')
log_file = os.path.join(log_dir, name + ".log")
fhandler = logging.FileHandler(log_file, "w", "utf-8")
shandler = logging.StreamHandler()

formatter = logging.Formatter(
"[%(name)s]" + str(' ' * (11 - len(name))) + "[%(asctime)s] [%(levelname)s] : %(message)s")
"[%(name)s]" + str(" " * (11 - len(name))) + "[%(asctime)s] [%(levelname)s] : %(message)s"
)
fhandler.setFormatter(formatter)
shandler.setFormatter(formatter)

logger.addHandler(fhandler)
logger.addHandler(shandler)

return logger
return logger
22 changes: 11 additions & 11 deletions piemc/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,25 +84,25 @@ def __init__(self, hostname, port):
self.logger.info(self.lang['SERVER_INITIALIZED'])
self.start_time = int(time.time())
initialize_commands(piemc.handlers.command)

def get_time_ms(self):
return round(time.time() - self.start_time, 4)

def update_server_status(self):
self.server_status = ';'.join([
self.server_status = ";".join([
self.edition,
self.motd,
str(self.protocol_version),
f"{self.protocol_version}",
self.version_name,
str(self.players_online),
str(self.max_players),
str(self.uid),
f"{self.players_online}",
f"{self.max_players}",
f"{self.uid}",
self.level,
self.gamemode[0],
str(self.gamemode[1]),
str(self.port),
str(self.port_v6)
]) + ';'
f"{self.gamemode[1]}",
f"{self.port}",
f"{self.port_v6}"
]) + ";"
self.raknet_server.name = self.server_status

def on_game_packet(self, packet: GamePacket, connection: Connection):
Expand Down
19 changes: 11 additions & 8 deletions piemc/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,28 @@
# @author PieMC Team
# @link http://www.PieMC-Dev.github.io/

import requests
import os
from pathlib import Path
from datetime import datetime

import requests


repo_url = "https://api.github.com/repos/PieMC-Dev/PieMC/releases"


def check_for_updates():
response = requests.get(repo_url)
if response.status_code == 200:
releases = response.json()

if releases:
latest_release = releases[0]
latest_version = latest_release['tag_name']
latest_date = datetime.strptime(latest_release['published_at'], "%Y-%m-%dT%H:%M:%SZ")
latest_version = latest_release["tag_name"]
latest_date = datetime.strptime(latest_release["published_at"], "%Y-%m-%dT%H:%M:%SZ")

version_file = os.path.join(os.path.dirname(__file__), "version.dat")
if os.path.exists(version_file):
with open(version_file, 'r') as file:
version_file = Path(Path(__file__).parent, "version.dat")
if version_file.exists():
with open(version_file, "r") as file:
current_date_str = file.read().strip()
current_date = datetime.strptime(current_date_str, "%Y-%m-%dT%H:%M:%SZ")
else:
Expand All @@ -45,4 +48,4 @@ def check_for_updates():
else:
print("No releases found for the repository.")
else:
print("Failed to retrieve repository information.")
print("Failed to retrieve repository information.")

0 comments on commit 0f252d3

Please sign in to comment.