From 8fbd2cc330247e197efa6f516988277024b8e32f Mon Sep 17 00:00:00 2001 From: santaspeen Date: Mon, 15 Jul 2024 11:39:31 +0300 Subject: [PATCH] [~] Update versions in req.txt [~] Rename register_event > register --- docs/cn/plugins/classes.md | 2 +- docs/cn/plugins/examples/async_example.py | 2 +- docs/cn/plugins/examples/example.py | 2 +- docs/cn/plugins/readme.md | 8 +-- docs/en/plugins/classes.md | 2 +- docs/en/plugins/examples/async_example.py | 2 +- docs/en/plugins/examples/example.py | 2 +- docs/en/plugins/readme.md | 8 +-- docs/ru/plugins/classes.md | 2 +- docs/ru/plugins/examples/async_example.py | 2 +- docs/ru/plugins/examples/example.py | 2 +- docs/ru/plugins/readme.md | 8 +-- requirements.txt | 8 +-- src/core/__init__.py | 3 +- src/core/core.py | 4 +- src/core/udp_server.py | 5 +- src/modules/ConfigProvider/__init__.py | 48 ++++++++++++++++- src/modules/ConfigProvider/config_provider.py | 54 ------------------- ...config_provider-builtins.pyi => readme.md} | 5 +- src/modules/EventsSystem/events_system.py | 5 +- .../EventsSystem/events_systems-builtins.pyi | 2 +- .../PluginsLoader/lua_plugins_loader.py | 6 +-- src/modules/PluginsLoader/plugins_loader.py | 10 ++-- 23 files changed, 93 insertions(+), 99 deletions(-) delete mode 100644 src/modules/ConfigProvider/config_provider.py rename src/modules/ConfigProvider/{config_provider-builtins.pyi => readme.md} (93%) diff --git a/docs/cn/plugins/classes.md b/docs/cn/plugins/classes.md index ad7eca6..33e55db 100644 --- a/docs/cn/plugins/classes.md +++ b/docs/cn/plugins/classes.md @@ -23,7 +23,7 @@ _常量_\ _与open()参数相同_\ 在kt.dir中打开文件 -### kt.register_event(event_name: str, event_func: function) +### kt.register(event_name: str, event_func: function) _`event_name: str` -> 作为`event_func`调用的事件名称._\ _`event_func: function` -> 要调用的函数._ diff --git a/docs/cn/plugins/examples/async_example.py b/docs/cn/plugins/examples/async_example.py index 1244eda..3f46270 100644 --- a/docs/cn/plugins/examples/async_example.py +++ b/docs/cn/plugins/examples/async_example.py @@ -21,7 +21,7 @@ async def load(): json.dump(config, f) cgf = config log.info(cgf) - ev.register_event("my_event", my_event_handler) + ev.register("my_event", my_event_handler) log.info("Плагин загружен успешно.") diff --git a/docs/cn/plugins/examples/example.py b/docs/cn/plugins/examples/example.py index 536a170..c20eb0f 100644 --- a/docs/cn/plugins/examples/example.py +++ b/docs/cn/plugins/examples/example.py @@ -21,7 +21,7 @@ def load(): json.dump(config, f) cgf = config log.info(cgf) - ev.register_event("my_event", my_event_handler) + ev.register("my_event", my_event_handler) log.info("Плагин загружен успешно.") diff --git a/docs/cn/plugins/readme.md b/docs/cn/plugins/readme.md index 8d45a2d..ae21311 100644 --- a/docs/cn/plugins/readme.md +++ b/docs/cn/plugins/readme.md @@ -28,7 +28,7 @@ def my_event_handler(event_data): def load(): # 初始化插件 - ev.register_event("my_event", my_event_handler) + ev.register("my_event", my_event_handler) log.info("插件已成功加载。") @@ -47,7 +47,7 @@ def unload(): 您还可以在[example.py](examples/example.py)中找到更广泛的示例。 * 建议在`load()`后使用`open()`,否则应使用`kt.load()`-在`plugin//`文件夹中创建一个文件 -* 创建自己的事件:`kt.register_event("my_event", my_event_function)`- +* 创建自己的事件:`kt.register("my_event", my_event_function)`- * 调用事件:`kt.call_event("my_event")` * 使用数据调用事件:`kt.call_event("my_event", data, data2=data2)` * 基本事件:_稍后会写_ @@ -72,7 +72,7 @@ async def my_event_handler(event_data): async def load(): # 初始化插件 - ev.register_event("my_event", my_event_handler) + ev.register("my_event", my_event_handler) log.info("插件已成功加载。") @@ -91,7 +91,7 @@ async def unload(): 您还可以在[async_example.py](examples/async_example.py)中找到更广泛的示例。 -* 创建自己的事件:`kt.register_event("my_event", my_event_function)`(在register_event中检查函数) +* 创建自己的事件:`kt.register("my_event", my_event_function)`(在register中检查函数) * 调用async事件:`kt.call_async_event("my_event")` * 使用数据调用async事件:`kt.call_async_event("my_event", data, data2=data2)` * 基本的async事件:_稍后会写_ diff --git a/docs/en/plugins/classes.md b/docs/en/plugins/classes.md index c91e5c3..db72cbc 100644 --- a/docs/en/plugins/classes.md +++ b/docs/en/plugins/classes.md @@ -23,7 +23,7 @@ Returns the directory of the plugin _Parameters are the same as for open()_\ Opens a file in kt.dir -### kt.register_event(event_name: str, event_func: function) +### kt.register(event_name: str, event_func: function) _`event_name: str` -> The name of the event that `event_func` will be called on._\ _`event_func: function` -> The function that will be called._ diff --git a/docs/en/plugins/examples/async_example.py b/docs/en/plugins/examples/async_example.py index 1244eda..3f46270 100644 --- a/docs/en/plugins/examples/async_example.py +++ b/docs/en/plugins/examples/async_example.py @@ -21,7 +21,7 @@ async def load(): json.dump(config, f) cgf = config log.info(cgf) - ev.register_event("my_event", my_event_handler) + ev.register("my_event", my_event_handler) log.info("Плагин загружен успешно.") diff --git a/docs/en/plugins/examples/example.py b/docs/en/plugins/examples/example.py index 536a170..c20eb0f 100644 --- a/docs/en/plugins/examples/example.py +++ b/docs/en/plugins/examples/example.py @@ -21,7 +21,7 @@ def load(): json.dump(config, f) cgf = config log.info(cgf) - ev.register_event("my_event", my_event_handler) + ev.register("my_event", my_event_handler) log.info("Плагин загружен успешно.") diff --git a/docs/en/plugins/readme.md b/docs/en/plugins/readme.md index 2a0113d..2987255 100644 --- a/docs/en/plugins/readme.md +++ b/docs/en/plugins/readme.md @@ -31,7 +31,7 @@ def my_event_handler(event_data): def load(): # Plugin initialization - kt.register_event("my_event", my_event_handler) + kt.register("my_event", my_event_handler) log.info("Plugin loaded successfully.") @@ -50,7 +50,7 @@ def unload(): A more comprehensive example can also be found in [example.py](examples/example.py) * It is recommended to use `open()` after `load()`, otherwise use `kt.load()` - It creates a file in the `plugin//` folder. -* Creating your own event: `kt.register_event("my_event", my_event_function)` - +* Creating your own event: `kt.register("my_event", my_event_function)` - * Calling an event: `kt.call_event("my_event")` * Calling an event with data: `kt.call_event("my_event", data, data2=data2)` * Base events: _To be added later_ @@ -75,7 +75,7 @@ async def my_event_handler(event_data): async def load(): # Plugin initialization - kt.register_event("my_event", my_event_handler) + kt.register("my_event", my_event_handler) log.info("Plugin loaded successfully.") @@ -94,7 +94,7 @@ async def unload(): A more comprehensive example can also be found in [async_example.py](examples/async_example.py) -* Creating your own event: `kt.register_event("my_event", my_event_function)` (register_event has a function check) +* Creating your own event: `kt.register("my_event", my_event_function)` (register has a function check) * Calling an async event: `kt.call_async_event("my_event")` * Calling an async event with data: `kt.call_async_event("my_event", data, data2=data2)` * Base async events: _To be added later_ \ No newline at end of file diff --git a/docs/ru/plugins/classes.md b/docs/ru/plugins/classes.md index e145988..a8a1a91 100644 --- a/docs/ru/plugins/classes.md +++ b/docs/ru/plugins/classes.md @@ -23,7 +23,7 @@ _Константа_\ _Параметры как у open()_\ Открывает файл в kt.dir -### kt.register_event(event_name: str, event_func: function) +### kt.register(event_name: str, event_func: function) _`event_name: str` -> Имя ивента, по которому будет вызвана `event_func`._\ _`event_func: function` -> Функция, которая будет вызвана._ diff --git a/docs/ru/plugins/examples/async_example.py b/docs/ru/plugins/examples/async_example.py index 1244eda..3f46270 100644 --- a/docs/ru/plugins/examples/async_example.py +++ b/docs/ru/plugins/examples/async_example.py @@ -21,7 +21,7 @@ async def load(): json.dump(config, f) cgf = config log.info(cgf) - ev.register_event("my_event", my_event_handler) + ev.register("my_event", my_event_handler) log.info("Плагин загружен успешно.") diff --git a/docs/ru/plugins/examples/example.py b/docs/ru/plugins/examples/example.py index 536a170..c20eb0f 100644 --- a/docs/ru/plugins/examples/example.py +++ b/docs/ru/plugins/examples/example.py @@ -21,7 +21,7 @@ def load(): json.dump(config, f) cgf = config log.info(cgf) - ev.register_event("my_event", my_event_handler) + ev.register("my_event", my_event_handler) log.info("Плагин загружен успешно.") diff --git a/docs/ru/plugins/readme.md b/docs/ru/plugins/readme.md index 244332c..e947b0f 100644 --- a/docs/ru/plugins/readme.md +++ b/docs/ru/plugins/readme.md @@ -28,7 +28,7 @@ def my_event_handler(event_data): def load(): # Инициализация плагина - ev.register_event("my_event", my_event_handler) + ev.register("my_event", my_event_handler) log.info("Плагин загружен успешно.") @@ -46,7 +46,7 @@ def unload(): Так же более обширный пример можно найти в [example.py](examples/example.py) * Рекомендуется использовать `open()` после `load()`, иначе стоит использовать `kt.load()` - Создаёт файл в папке `plugin//` -* Создание своего ивента : `kt.register_event("my_event", my_event_function)` - +* Создание своего ивента : `kt.register("my_event", my_event_function)` - * Вызов ивента: `kt.call_event("my_event")` * Вызов ивента с данными: `kt.call_event("my_event", data, data2=data2)` * Базовые ивенты: _Позже напишу_ @@ -71,7 +71,7 @@ async def my_event_handler(event_data): async def load(): # Инициализация плагина - ev.register_event("my_event", my_event_handler) + ev.register("my_event", my_event_handler) log.info("Плагин загружен успешно.") @@ -90,7 +90,7 @@ async def unload(): Так же более обширный пример можно найти в [async_example.py](examples/async_example.py) -* Создание своего ивента: `kt.register_event("my_event", my_event_function)` (в register_event стоит проверка на функцию) +* Создание своего ивента: `kt.register("my_event", my_event_function)` (в register стоит проверка на функцию) * Вызов async ивента: `kt.call_async_event("my_event")` * Вызов async ивента: `kt.call_async_event("my_event", data, data2=data2)` * Базовые async ивенты: _Позже напишу_ diff --git a/requirements.txt b/requirements.txt index 63755e0..f3399fc 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,12 +1,12 @@ PyYAML~=6.0 prompt-toolkit~=3.0.38 -aiohttp~=3.8.4 +aiohttp~=3.9.5 uvicorn~=0.22.0 -fastapi~=0.100.0 -starlette~=0.27.0 +fastapi~=0.109.1 +starlette~=0.36.2 pydantic~=2.0.2 click~=8.1.4 lupa~=2.0 toml~=0.10.2 colorama~=0.4.6 -cryptography~=41.0.2 \ No newline at end of file +cryptography~=42.0.4 \ No newline at end of file diff --git a/src/core/__init__.py b/src/core/__init__.py index 259ffcd..63e9104 100644 --- a/src/core/__init__.py +++ b/src/core/__init__.py @@ -4,8 +4,7 @@ # Version 1.5 # Core version: 0.4.5 # Licence: FPA -# (c) kuitoi.su 2023 -# Special thanks to: AI Sage(https://poe.com/Sage), AI falcon-40b-v7(https://OpenBuddy.ai) +# (c) kuitoi.su 2024 __title__ = 'KuiToi-Server' __description__ = 'BeamingDrive Multiplayer server compatible with BeamMP clients.' diff --git a/src/core/core.py b/src/core/core.py index efa5659..b0d82f4 100644 --- a/src/core/core.py +++ b/src/core/core.py @@ -49,8 +49,8 @@ class Core: self.client_major_version = "2.0" self.BeamMP_version = "3.1.1" # 20.07.2023 - ev.register_event("_get_BeamMP_version", lambda x: tuple([int(i) for i in self.BeamMP_version.split(".")])) - ev.register_event("_get_player", lambda x: self.get_client(**x['kwargs'])) + ev.register("_get_BeamMP_version", lambda x: tuple([int(i) for i in self.BeamMP_version.split(".")])) + ev.register("_get_player", lambda x: self.get_client(**x['kwargs'])) def get_client(self, cid=None, nick=None): if cid is None and nick is None: diff --git a/src/core/udp_server.py b/src/core/udp_server.py index 243a1e1..9240f52 100644 --- a/src/core/udp_server.py +++ b/src/core/udp_server.py @@ -3,7 +3,7 @@ # Written by: SantaSpeen # Core version: 0.4.5 # Licence: FPA -# (c) kuitoi.su 2023 +# (c) kuitoi.su 2024 import asyncio import json @@ -109,4 +109,5 @@ class UDPServer(asyncio.DatagramTransport): def _stop(self): self.log.debug("Stopping UDP server") - self.transport.close() + if self.transport: + self.transport.close() diff --git a/src/modules/ConfigProvider/__init__.py b/src/modules/ConfigProvider/__init__.py index 84da03f..7c7303d 100644 --- a/src/modules/ConfigProvider/__init__.py +++ b/src/modules/ConfigProvider/__init__.py @@ -6,4 +6,50 @@ # Version 1.0 # Licence: FPA # (c) kuitoi.su 2023 -from .config_provider import ConfigProvider, Config +import os +import secrets + +import yaml + + +class Config: + def __init__(self, auth=None, game=None, server=None, rcon=None, options=None, web=None): + self.Auth = auth or {"key": None, "private": True} + self.Game = game or {"map": "gridmap_v2", "players": 8, "max_cars": 1} + self.Server = server or {"name": "KuiToi-Server", "description": "Welcome to KuiToi Server!", + "server_ip": "0.0.0.0", "server_port": 30814} + self.RCON = rcon or {"enabled": False, "server_ip": "127.0.0.1", "server_port": 10383, + "password": secrets.token_hex(16)} + self.Options = options or {"language": "en", "encoding": "utf-8", "speed_limit": 0, "use_queue": False, + "debug": False, "use_lua": False, "log_chat": True} + self.WebAPI = web or {"enabled": False, "server_ip": "127.0.0.1", "server_port": 8433, + "access_token": secrets.token_hex(16)} + + def __repr__(self): + return f"{self.__class__.__name__}(Auth={self.Auth!r}, Game={self.Game!r}, Server={self.Server!r}, " \ + f"RCON={self.RCON!r}, Options={self.Options!r}, WebAPI={self.WebAPI!r})" + + +class ConfigProvider: + + def __init__(self, config_path): + self.config_path = config_path + self.config = Config() + + def open_config(self): + if not os.path.exists(self.config_path): + with open(self.config_path, "w", encoding="utf-8") as f: + yaml.dump(self.config, f) + try: + with open(self.config_path, "r", encoding="utf-8") as f: + self.config = yaml.load(f.read(), yaml.Loader) + except yaml.YAMLError: + print("You have errors in the YAML syntax.") + print("Stopping server.") + exit(1) + + return self.config + + def save_config(self): + with open(self.config_path, "w", encoding="utf-8") as f: + yaml.dump(self.config, f) diff --git a/src/modules/ConfigProvider/config_provider.py b/src/modules/ConfigProvider/config_provider.py deleted file mode 100644 index cb95101..0000000 --- a/src/modules/ConfigProvider/config_provider.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- -# Developed by KuiToi Dev -# File modules.config_provider.config_provider.py -# Written by: SantaSpeen -# Version 1.1 -# Licence: FPA -# (c) kuitoi.su 2023 -import os -import secrets - -import yaml - - -class Config: - def __init__(self, auth=None, game=None, server=None, rcon=None, options=None, web=None): - self.Auth = auth or {"key": None, "private": True} - self.Game = game or {"map": "gridmap_v2", "players": 8, "max_cars": 1} - self.Server = server or {"name": "KuiToi-Server", "description": "Welcome to KuiToi Server!", - "server_ip": "0.0.0.0", "server_port": 30814} - self.RCON = rcon or {"enabled": False, "server_ip": "127.0.0.1", "server_port": 10383, - "password": secrets.token_hex(16)} - self.Options = options or {"language": "en", "encoding": "utf-8", "speed_limit": 0, "use_queue": False, - "debug": False, "use_lua": False, "log_chat": True} - self.WebAPI = web or {"enabled": False, "server_ip": "127.0.0.1", "server_port": 8433, - "access_token": secrets.token_hex(16)} - - def __repr__(self): - return f"{self.__class__.__name__}(Auth={self.Auth!r}, Game={self.Game!r}, Server={self.Server!r}, " \ - f"RCON={self.RCON!r}, Options={self.Options!r}, WebAPI={self.WebAPI!r})" - - -class ConfigProvider: - - def __init__(self, config_path): - self.config_path = config_path - self.config = Config() - - def open_config(self): - if not os.path.exists(self.config_path): - with open(self.config_path, "w", encoding="utf-8") as f: - yaml.dump(self.config, f) - try: - with open(self.config_path, "r", encoding="utf-8") as f: - self.config = yaml.load(f.read(), yaml.Loader) - except yaml.YAMLError: - print("You have errors in the YAML syntax.") - print("Stopping server.") - exit(1) - - return self.config - - def save_config(self): - with open(self.config_path, "w", encoding="utf-8") as f: - yaml.dump(self.config, f) diff --git a/src/modules/ConfigProvider/config_provider-builtins.pyi b/src/modules/ConfigProvider/readme.md similarity index 93% rename from src/modules/ConfigProvider/config_provider-builtins.pyi rename to src/modules/ConfigProvider/readme.md index ec7f07b..3b00cf2 100644 --- a/src/modules/ConfigProvider/config_provider-builtins.pyi +++ b/src/modules/ConfigProvider/readme.md @@ -1,6 +1,6 @@ -from typing import Dict - +### Builtins +```python class Config: Auth: Dict[str, object] Game: Dict[str, object] @@ -12,3 +12,4 @@ class Config: def __repr__(self): return "%s(Auth=%r, Game=%r, Server=%r)" % (self.__class__.__name__, self.Auth, self.Game, self.Server) class config (Config): ... +``` \ No newline at end of file diff --git a/src/modules/EventsSystem/events_system.py b/src/modules/EventsSystem/events_system.py index 02a0f07..67f4d68 100644 --- a/src/modules/EventsSystem/events_system.py +++ b/src/modules/EventsSystem/events_system.py @@ -68,6 +68,7 @@ class EventsSystem: "onFileChanged": [], # TODO lua onFileChanged "onConsoleInput": [], # kt.add_command } + self.register_event = self.register def builtins_hook(self): self.log.debug("used builtins_hook") @@ -78,8 +79,8 @@ class EventsSystem: event_name in self.__events.keys() or event_name in self.__lua_events.keys()) - def register_event(self, event_name, event_func, async_event=False, lua=None): - self.log.debug(f"register_event(event_name='{event_name}', event_func='{event_func}', " + def register(self, event_name, event_func, async_event=False, lua=None): + self.log.debug(f"register(event_name='{event_name}', event_func='{event_func}', " f"async_event={async_event}, lua_event={lua}):") if lua: if event_name not in self.__lua_events: diff --git a/src/modules/EventsSystem/events_systems-builtins.pyi b/src/modules/EventsSystem/events_systems-builtins.pyi index bc33af8..6616288 100644 --- a/src/modules/EventsSystem/events_systems-builtins.pyi +++ b/src/modules/EventsSystem/events_systems-builtins.pyi @@ -3,7 +3,7 @@ from typing import Any class EventsSystem: @staticmethod - def register_event(event_name, event_func, async_event: bool = False, lua: bool | object = None): ... + def register(event_name, event_func, async_event: bool = False, lua: bool | object = None): ... @staticmethod async def call_async_event(event_name, *args, **kwargs) -> list[Any]: ... @staticmethod diff --git a/src/modules/PluginsLoader/lua_plugins_loader.py b/src/modules/PluginsLoader/lua_plugins_loader.py index 03b9e1f..d5261db 100644 --- a/src/modules/PluginsLoader/lua_plugins_loader.py +++ b/src/modules/PluginsLoader/lua_plugins_loader.py @@ -88,7 +88,7 @@ class MP: def RegisterEvent(self, event_name: str, function_name: str) -> None: self.log.debug("request MP.RegisterEvent()") - ev.register_event(event_name, function_name, lua=self._lua) + ev.register(event_name, function_name, lua=self._lua) if event_name not in self._local_events: self._local_events.update({str(event_name): [function_name]}) else: @@ -577,8 +577,8 @@ class LuaPluginsLoader: self.lua_dirs = set() self.log = get_logger("LuaPluginsLoader") self.loaded_str = "Lua plugins: " - ev.register_event("_lua_plugins_get", lambda x: self.lua_plugins) - ev.register_event("_lua_plugins_unload", self.unload) + ev.register("_lua_plugins_get", lambda x: self.lua_plugins) + ev.register("_lua_plugins_unload", self.unload) console.add_command("lua_plugins", lambda x: self.loaded_str[:-2]) console.add_command("lua_pl", lambda x: self.loaded_str[:-2]) diff --git a/src/modules/PluginsLoader/plugins_loader.py b/src/modules/PluginsLoader/plugins_loader.py index 858759f..da295e2 100644 --- a/src/modules/PluginsLoader/plugins_loader.py +++ b/src/modules/PluginsLoader/plugins_loader.py @@ -57,9 +57,9 @@ class KuiToi: if f is not None: f.close() - def register_event(self, event_name, event_func): + def register(self, event_name, event_func): self.log.debug(f"Registering event {event_name}") - ev.register_event(event_name, event_func) + ev.register(event_name, event_func) def call_event(self, event_name, *args, **kwargs): self.log.debug(f"Called event {event_name}") @@ -105,9 +105,9 @@ class PluginsLoader: self.plugins_dir = plugins_dir self.log = get_logger("PluginsLoader") self.loaded_str = "Plugins: " - ev.register_event("_plugins_start", self.start) - ev.register_event("_plugins_unload", self.unload) - ev.register_event("_plugins_get", lambda x: list(self.plugins.keys())) + ev.register("_plugins_start", self.start) + ev.register("_plugins_unload", self.unload) + ev.register("_plugins_get", lambda x: list(self.plugins.keys())) console.add_command("plugins", lambda x: self.loaded_str[:-2]) console.add_command("pl", lambda x: self.loaded_str[:-2])