Skip to content

Commit

Permalink
New features
Browse files Browse the repository at this point in the history
Improved command handling (Now commands are created in commands folder)
Moved Logger from server.py to an independent handler
  • Loading branch information
andiricum2 committed Aug 1, 2023
1 parent 4163cbf commit 4f9073d
Show file tree
Hide file tree
Showing 5 changed files with 84 additions and 59 deletions.
Empty file added piemc/commands/__init__.py
Empty file.
11 changes: 11 additions & 0 deletions piemc/commands/piemc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
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()

40 changes: 17 additions & 23 deletions piemc/handlers/command.py
Original file line number Diff line number Diff line change
@@ -1,27 +1,21 @@
from piemc.handlers.lang import LangHandler
import inspect

registered_commands = {}

class CommandHandler:
def __init__(self, logger):
self.logger = logger
def Command(func):
cmd_name = func.__name__.lower()
registered_commands[cmd_name] = func
return func

def handle(self, cmd, server):
self.lang = LangHandler.initialize_language()
if cmd == 'stop':
self.handle_stop_cmd(server)
elif cmd == 'restart':
self.handle_restart_cmd(server)
elif cmd == '':
print(self.lang['EMPTY_COMMAND'])
def handle_command(server, cmd):
cmd_args = cmd.strip().split()
cmd_name = cmd_args[0].lower()

func = registered_commands.get(cmd_name)
if func is not None:
if inspect.getfullargspec(func).args:
func(server, *cmd_args[1:])
else:
print(self.lang['NOT_A_COMMAND'].format(cmd))

def handle_stop_cmd(self, server):
self.logger.info(self.lang['STOPPING'])
server.stop()

def handle_restart_cmd(self, server):
self.logger.info(self.lang['RESTARTING'])
self.logger.error('This command in development now')
# server.stop()
# server.start()
func(server)
else:
print(f"Command '{cmd_name}' not found.")
32 changes: 32 additions & 0 deletions piemc/handlers/logger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import logging
import os
import piemc.config # Assuming you have a config module with LOG_LEVEL defined

def create_logger(name):
log_level_mapping = {
'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'
os.makedirs(log_dir, exist_ok=True) # Create the directory if it doesn't exist

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")
fhandler.setFormatter(formatter)
shandler.setFormatter(formatter)

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

return logger
60 changes: 24 additions & 36 deletions piemc/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,17 @@
import random
import threading
import time
import importlib
import pkgutil
import inspect


from piemc import config
from piemc.handlers.command import CommandHandler
from piemc.handlers.command import handle_command
from piemc.handlers.lang import LangHandler
from piemc.meta.protocol_info import ProtocolInfo
import piemc.commands
from piemc.handlers.logger import create_logger

from pieraknet import Server
from pieraknet.packets.game_packet import GamePacket
Expand All @@ -36,7 +42,7 @@ def __init__(self, hostname, port):
self.threads = []
self.lang = LangHandler.initialize_language()
print(self.lang['INITIALIZING'])
self.logger = self.create_logger('PieMC')
self.logger = create_logger('PieMC')
if not os.path.exists("pieuid.dat"):
pieuid = random.randint(10 ** 19, (10 ** 20) - 1)
with open("pieuid.dat", "w") as uid_file:
Expand Down Expand Up @@ -67,7 +73,7 @@ def __init__(self, hostname, port):
self.uid = pieuid
self.raknet_version = 11
self.timeout = 20
self.raknet_server = Server(self.hostname, self.port, self.create_logger('PieRakNet'))
self.raknet_server = Server(self.hostname, self.port, create_logger('PieRakNet'))
self.raknet_server.interface = self
self.update_server_status()
self.raknet_server.name = self.server_status
Expand All @@ -78,43 +84,25 @@ def __init__(self, hostname, port):
self.raknet_thread.daemon = True
self.threads.append(self.raknet_thread)
self.running = False
self.cmd_handler = CommandHandler(self.create_logger('CMD Handler'))
self.cmd_handler = handle_command
self.logger.info(self.lang['SERVER_INITIALIZED'])
self.start_time = int(time.time())

self.initialize_commands()

def initialize_commands(self):
command_modules = []
for importer, modname, ispkg in pkgutil.walk_packages(piemc.commands.__path__, piemc.commands.__name__ + '.'):
module = importlib.import_module(modname)
command_modules.append(module)

for module in command_modules:
for name, obj in inspect.getmembers(module, inspect.isclass):
if hasattr(obj, 'Command'):
setattr(self, name.lower(), obj(self.logger, self))

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

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

log_dir = './log'
os.makedirs(log_dir, exist_ok=True) # Create the directory if it doesn't exist

log_file = os.path.join(log_dir, name)
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")
fhandler.setFormatter(formatter)
shandler.setFormatter(formatter)

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

return logger

def update_server_status(self):
self.server_status = ';'.join([
self.edition,
Expand Down Expand Up @@ -159,7 +147,7 @@ def start(self):
check_for_updates()
while self.running:
cmd = input('>>> ')
self.cmd_handler.handle(cmd, self)
self.cmd_handler(self, cmd) # Call self.cmd_handler instead of handle_command
time.sleep(.1)

def stop(self):
Expand Down

0 comments on commit 4f9073d

Please sign in to comment.