From 4db97248ca9ab3c712073cb26fe71cbc6066be45 Mon Sep 17 00:00:00 2001 From: Sven Heidemann Date: Mon, 27 Dec 2021 19:32:12 +0100 Subject: [PATCH] Improved config loading --- src/gismo/appsettings.example.json | 36 ------------------- src/gismo/{ => config}/appsettings.json | 0 src/gismo/config/base.json | 2 ++ src/gismo/config/boot_log.json | 10 ++++++ src/gismo/config/database.json | 2 ++ src/gismo/startup.py | 6 ++-- .../configuration/discord_settings.py | 2 +- src/modules/boot_log/boot_log.py | 16 ++++++--- src/modules/boot_log/boot_log_settings.py | 29 +++++++++++++++ src/modules_core/abc/module_abc.py | 19 ++++++---- src/modules_core/service/module_service.py | 19 ++++++++-- 11 files changed, 87 insertions(+), 54 deletions(-) delete mode 100644 src/gismo/appsettings.example.json rename src/gismo/{ => config}/appsettings.json (100%) create mode 100644 src/gismo/config/base.json create mode 100644 src/gismo/config/boot_log.json create mode 100644 src/gismo/config/database.json create mode 100644 src/modules/boot_log/boot_log_settings.py diff --git a/src/gismo/appsettings.example.json b/src/gismo/appsettings.example.json deleted file mode 100644 index 7bd96f0..0000000 --- a/src/gismo/appsettings.example.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "TimeFormatSettings": { - "DateFormat": "%Y-%m-%d", - "TimeFormat": "%H:%M:%S", - "DateTimeFormat": "%Y-%m-%d %H:%M:%S.%f", - "DateTimeLogFormat": "%Y-%m-%d_%H-%M-%S" - }, - "LoggingSettings": { - "Path": "logs/", - "Filename": "log_$start_time.log", - "ConsoleLogLevel": "ERROR", - "FileLogLevel": "WARN" - }, - "Discord": { - "Token": "" - }, - "Bot": { - "Prefix": "!g", - "Servers": [ - { - "Id": "", - "LoginMessageChannelId": "", - "LoginMessage": "", - "MessageDeleteTimer": 0, - "WelcomeMessage": "", - "GoodbyeMessage": "", - "MaxVoiceStateHours": 0, - "XpPerMessage": 0, - "XpPerOntimeHour": 0, - "AFKChannelIds": [], - "AdminRoleIds": [], - "ModeratorRoleIds": [] - } - ] - } -} \ No newline at end of file diff --git a/src/gismo/appsettings.json b/src/gismo/config/appsettings.json similarity index 100% rename from src/gismo/appsettings.json rename to src/gismo/config/appsettings.json diff --git a/src/gismo/config/base.json b/src/gismo/config/base.json new file mode 100644 index 0000000..7a73a41 --- /dev/null +++ b/src/gismo/config/base.json @@ -0,0 +1,2 @@ +{ +} \ No newline at end of file diff --git a/src/gismo/config/boot_log.json b/src/gismo/config/boot_log.json new file mode 100644 index 0000000..f54b141 --- /dev/null +++ b/src/gismo/config/boot_log.json @@ -0,0 +1,10 @@ +{ + "910199451145076828": { + "LoginMessageChannelId": "910199452915093588", + "LoginMessage": "Ich bin on the line :D\nDer Start hat {} Sekunden gedauert" + }, + "511824600884051979": { + "LoginMessageChannelId": "521260270757347328", + "LoginMessage": "Ich bin on the line :D\nDer Start hat {} Sekunden gedauert" + } +} \ No newline at end of file diff --git a/src/gismo/config/database.json b/src/gismo/config/database.json new file mode 100644 index 0000000..7a73a41 --- /dev/null +++ b/src/gismo/config/database.json @@ -0,0 +1,2 @@ +{ +} \ No newline at end of file diff --git a/src/gismo/startup.py b/src/gismo/startup.py index 1d38c1d..fbdd7cf 100644 --- a/src/gismo/startup.py +++ b/src/gismo/startup.py @@ -54,9 +54,9 @@ class Startup(StartupABC): environment.set_working_directory(os.path.dirname(os.path.realpath(__file__))) configuration.add_environment_variables('GISMO_') - configuration.add_json_file(f'appsettings.json', optional=False) - configuration.add_json_file(f'appsettings.{environment.environment_name}.json', optional=True) - configuration.add_json_file(f'appsettings.{environment.host_name}.json', optional=True) + configuration.add_json_file(f'config/appsettings.json', optional=False) + configuration.add_json_file(f'config/appsettings.{environment.environment_name}.json', optional=True) + configuration.add_json_file(f'config/appsettings.{environment.host_name}.json', optional=True) configuration.add_configuration('Startup_StartTime', self._start_time) diff --git a/src/gismo_core/configuration/discord_settings.py b/src/gismo_core/configuration/discord_settings.py index efec204..84d323b 100644 --- a/src/gismo_core/configuration/discord_settings.py +++ b/src/gismo_core/configuration/discord_settings.py @@ -19,5 +19,5 @@ class DiscordSettings(ConfigurationModelABC): try: self._token = settings['Token'] except Exception as e: - Console.error(f'[ ERROR ] [ {__name__} ]: Reading error in {self.__name__} settings') + Console.error(f'[ ERROR ] [ {__name__} ]: Reading error in {__name__} settings') Console.error(f'[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}') diff --git a/src/modules/boot_log/boot_log.py b/src/modules/boot_log/boot_log.py index 4ee4834..cd07e80 100644 --- a/src/modules/boot_log/boot_log.py +++ b/src/modules/boot_log/boot_log.py @@ -8,6 +8,7 @@ from discord import guild from gismo_core.abc.bot_service_abc import BotServiceABC from gismo_core.abc.message_service_abc import MessageServiceABC from gismo_core.configuration.server_settings import ServerSettings +from modules.boot_log.boot_log_settings import BootLogSettings from modules_core.abc.events.on_ready_abc import OnReadyABC from modules_core.abc.module_abc import ModuleABC @@ -26,11 +27,16 @@ class BootLog(ModuleABC, OnReadyABC): self._logger = logger self._bot = bot self._message_service = message_service - - ModuleABC.__init__(self) - self._priorities[OnReadyABC] = 10 + + ModuleABC.__init__( + self, + { + OnReadyABC: 10 + }, + BootLogSettings + ) self._logger.trace(__name__, f'Module {type(self)} loaded') - + async def on_ready(self): self._logger.debug(__name__, f'Module {type(self)} started') try: @@ -69,4 +75,4 @@ class BootLog(ModuleABC, OnReadyABC): server_settings.login_message.format(init_time) ) - self._logger.trace(__name__, f'Module {type(self)} stopped') \ No newline at end of file + self._logger.trace(__name__, f'Module {type(self)} stopped') diff --git a/src/modules/boot_log/boot_log_settings.py b/src/modules/boot_log/boot_log_settings.py new file mode 100644 index 0000000..ea8611e --- /dev/null +++ b/src/modules/boot_log/boot_log_settings.py @@ -0,0 +1,29 @@ +import traceback + +from cpl_core.configuration.configuration_model_abc import ConfigurationModelABC +from cpl_core.console import Console + + +class BootLogSettings(ConfigurationModelABC): + + def __init__(self): + ConfigurationModelABC.__init__(self) + + self._login_message_channel_id: int = 0 + self._login_message: str = '' + + @property + def login_message_channel_id(self) -> int: + return self._login_message_channel_id + + @property + def login_message(self) -> str: + return self._login_message + + def from_dict(self, settings: dict): + try: + self._login_message_channel_id = int(settings['LoginMessageChannelId']) + self._login_message = settings['LoginMessage'] + except Exception as e: + Console.error(f'[ ERROR ] [ {__name__} ]: Reading error in {__name__} settings') + Console.error(f'[ EXCEPTION ] [ {__name__} ]: {e} -> {traceback.format_exc()}') diff --git a/src/modules_core/abc/module_abc.py b/src/modules_core/abc/module_abc.py index d860319..7829e32 100644 --- a/src/modules_core/abc/module_abc.py +++ b/src/modules_core/abc/module_abc.py @@ -1,12 +1,23 @@ from abc import ABC, abstractmethod +from typing import Optional +from cpl_core.configuration import ConfigurationModelABC class ModuleABC(ABC): @abstractmethod - def __init__(self): - self._priorities = {} + def __init__(self, priorities: dict[type, int], settings_type: type): + self._priorities = priorities self._success = True + self._settings_type = settings_type + + @property + def success(self) -> bool: + return self._success + + @property + def settings_type(self) -> type: + return self._settings_type def get_priority(self, t: type) -> int: if t not in self._priorities: @@ -15,7 +26,3 @@ class ModuleABC(ABC): def stop_propagation(self): self._success = False - - @property - def success(self) -> bool: - return self._success diff --git a/src/modules_core/service/module_service.py b/src/modules_core/service/module_service.py index 2d16bf6..965e0f6 100644 --- a/src/modules_core/service/module_service.py +++ b/src/modules_core/service/module_service.py @@ -1,8 +1,10 @@ from abc import ABC, ABCMeta from datetime import datetime +import json from typing import Optional, Sequence, Union import discord +from cpl_core.configuration import ConfigurationModelABC, ConfigurationABC from cpl_core.dependency_injection import ServiceProviderABC from cpl_core.environment import ApplicationEnvironmentABC from cpl_core.logging import LoggerABC @@ -64,8 +66,9 @@ class _MetaCogABC(ABCMeta, commands.CogMeta): pass class ModuleService(ModuleServiceABC, commands.Cog, metaclass=_MetaCogABC): - def __init__(self, logger: LoggerABC, services: ServiceProviderABC, env: ApplicationEnvironmentABC): + def __init__(self, logger: LoggerABC, config: ConfigurationABC, services: ServiceProviderABC, env: ApplicationEnvironmentABC): self._logger = logger + self._config = config self._services = services self._env = env self._modules: List[ModuleABC] = List() @@ -75,12 +78,21 @@ class ModuleService(ModuleServiceABC, commands.Cog, metaclass=_MetaCogABC): module_types = self._modules.where(lambda m: issubclass(m, t)) modules = List(t) for module_type in module_types: - module = self._services.get_service(module_type) + module: ModuleABC = self._services.get_service(module_type) if module is None: self._logger.warn(__name__, f'Module {module_type} not found in services!') break + + with open(f'config/{String.convert_to_snake_case(type(module).__name__).lower()}.json', encoding='utf-8') as cfg: + json_cfg = json.load(cfg) + for id in json_cfg: + settings: ConfigurationModelABC = module.settings_type() + settings.from_dict(json_cfg[id]) + self._config.add_configuration(f'{type(module).__name__}_{id}', settings) + self._logger.debug(__name__, f'Added config: {type(module).__name__}_{id}') + modules.append(module) - + return modules.order_by(lambda m: m.get_priority(t)) async def _handle_event(self, event: type, *args): @@ -94,6 +106,7 @@ class ModuleService(ModuleServiceABC, commands.Cog, metaclass=_MetaCogABC): func_name = String.convert_to_snake_case(event.__name__.split('ABC')[0]) for module in modules: func = getattr(module, func_name) + exit() await func(*args) if not module.success: self._logger.debug(__name__, f'Stopped propagation for {event} from {type(module)}')