Skip to content

Commit

Permalink
Bug fixes + Optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
andiricum2 committed Aug 1, 2023
1 parent 4f9073d commit 23e2143
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 41 deletions.
3 changes: 1 addition & 2 deletions piemc/commands/piemc.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,4 @@ def ping(self):
@Command
def stop(self):
self.logger.info("Stopping the server...")
self.stop()

self.stop()
22 changes: 21 additions & 1 deletion piemc/handlers/command.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import importlib
import inspect
import pkgutil
import piemc.commands

registered_commands = {}

Expand All @@ -8,7 +11,12 @@ def Command(func):
return func

def handle_command(server, cmd):
cmd_args = cmd.strip().split()
cmd = cmd.strip()
if not cmd:
print("Please enter a command.")
return

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

func = registered_commands.get(cmd_name)
Expand All @@ -19,3 +27,15 @@ 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__ + '.'

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'))

for command_class in command_classes:
setattr(self, command_class.__name__.lower(), command_class(self.logger, self))
31 changes: 17 additions & 14 deletions piemc/handlers/lang.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,31 +14,34 @@
# @link http://www.PieMC-Dev.github.io/

import yaml
import os

from pathlib import Path
from piemc import config


class LangHandler:
lang_cache = None

@staticmethod
def initialize_language():
if LangHandler.lang_cache is not None:
return LangHandler.lang_cache

current_dir = Path(__file__).resolve().parent.parent
lang_dirname = "lang"
lang_fullpath = os.path.join(current_dir, lang_dirname)
lang_file_path = os.path.join(lang_fullpath, f"{config.LANG}.yml")
fallback_lang_file_path = os.path.join(lang_fullpath, "en.yml")
lang_fullpath = current_dir / lang_dirname
lang_file_path = lang_fullpath / f"{config.LANG}.yml"
fallback_lang_file_path = lang_fullpath / "en.yml"

if not os.path.exists(lang_file_path):
print(f"Language file not found for language: {config.LANG}")
lang = {}
else:
with open(lang_file_path, 'r', encoding='utf-8') as lang_file:
lang = {}
if lang_file_path.exists():
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 os.path.exists(fallback_lang_file_path):
with open(fallback_lang_file_path, 'r', encoding='utf-8') as fallback_lang_file:
if fallback_lang_file_path.exists():
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}

return lang
LangHandler.lang_cache = lang
return lang
4 changes: 2 additions & 2 deletions piemc/handlers/logger.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging
import os
import piemc.config # Assuming you have a config module with LOG_LEVEL defined
import piemc.config

def create_logger(name):
log_level_mapping = {
Expand All @@ -15,7 +15,7 @@ def create_logger(name):
logger.setLevel(log_level)

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

log_file = os.path.join(log_dir, name + '.log')
fhandler = logging.FileHandler(log_file, 'w', 'utf-8')
Expand Down
28 changes: 6 additions & 22 deletions piemc/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,36 +13,32 @@
# @author PieMC Team
# @link http://www.PieMC-Dev.github.io/

import logging
import os
import random
import threading
import time
import importlib
import pkgutil
import inspect


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

from pieraknet import Server
from pieraknet.packets.game_packet import GamePacket
from pieraknet.packets.frame_set import Frame
from pieraknet.connection import Connection

from piemc.update import check_for_updates

class MCBEServer:
def __init__(self, hostname, port):
self.threads = []
self.lang = LangHandler.initialize_language()
print(self.lang['INITIALIZING'])
self.logger = create_logger('PieMC')
self.logger.info(self.lang['INITIALIZING'])
if not os.path.exists("pieuid.dat"):
pieuid = random.randint(10 ** 19, (10 ** 20) - 1)
with open("pieuid.dat", "w") as uid_file:
Expand All @@ -64,7 +60,7 @@ def __init__(self, hostname, port):
"adventure": ("Adventure", 3)
}
self.gamemode = self.gamemode_map.get(config.GAMEMODE.lower(), ("Survival", 0))
print(self.lang['NOT_EXISTING_GAMEMODE']) if self.gamemode[1] == 0 else None
self.logger.info(self.lang['NOT_EXISTING_GAMEMODE']) if self.gamemode[1] == 0 else None
self.port = config.PORT
self.port_v6 = 19133
self.guid = random.randint(1, 99999999)
Expand All @@ -87,18 +83,7 @@ def __init__(self, hostname, port):
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))
initialize_commands(piemc.handlers.command)

def get_time_ms(self):
return round(time.time() - self.start_time, 4)
Expand Down Expand Up @@ -148,8 +133,7 @@ def start(self):
while self.running:
cmd = input('>>> ')
self.cmd_handler(self, cmd) # Call self.cmd_handler instead of handle_command
time.sleep(.1)


def stop(self):
self.logger.info(self.lang['STOPPING_WAIT'])
self.running = False
Expand Down

0 comments on commit 23e2143

Please sign in to comment.