36 Commits

Author SHA1 Message Date
4974d48411 0.2.2 -> 0.2.3 2023-07-16 03:07:47 +03:00
3b7842aa50 Update modules version 2023-07-16 03:06:38 +03:00
db6eb361b8 0.2.2 -> 0.2.3 2023-07-16 03:06:22 +03:00
479525a66e Remove nick, roles from protected;
Change _tcp_send -> _send;
Now _send data may be str;
Rewrite to_all handler;
Add chat handler;
2023-07-16 02:55:09 +03:00
6d4bc1e72c Minor update 2023-07-16 02:52:20 +03:00
9b3677de46 Minor update 2023-07-16 02:52:15 +03:00
58137752c5 Add commands plugins, pl 2023-07-16 02:50:25 +03:00
220c6068e4 Minor update 2023-07-16 02:49:58 +03:00
a9dad5ab8f Add codes to _looper();
Rewrite _tcp_send(to_all=True)
2023-07-15 19:00:21 +03:00
aa5725e8a5 Minor fix 2023-07-15 18:03:22 +03:00
939723acdd Add event player_join 2023-07-15 17:54:59 +03:00
90beaf1302 Refactor class Client to protected funcs and vars 2023-07-15 17:54:08 +03:00
ee366a2d23 Update TODOs 2023-07-15 17:04:12 +03:00
d665021479 i18n: Update en translate 2023-07-15 17:01:58 +03:00
13ff3207b2 Update en docs 2023-07-15 16:32:07 +03:00
50b479c396 Update docs 2023-07-15 16:21:43 +03:00
62fa4c6f25 Update docs 2023-07-15 16:20:37 +03:00
f0f8da962e Update async logic;
New except;
2023-07-15 15:37:55 +03:00
840d8fd685 New except 2023-07-15 15:36:59 +03:00
4629fbc43a Update Async logic 2023-07-15 15:36:45 +03:00
e9919459af Update Async logic 2023-07-15 15:34:24 +03:00
5f8b70a2ee Update version 2023-07-15 11:03:05 +03:00
a66f3d8b36 Update TODOs 2023-07-15 11:00:46 +03:00
4c3da30a94 Add new events. 2023-07-15 10:59:50 +03:00
9c52e41b99 Add new logs to class KuiToi;
load:
    Add encoding to open();
    Add plugin attributes error;
    Add plugin.start();
    Add plugin.unload();
    Recreate plugin settings;
    Add async support;
2023-07-15 10:59:33 +03:00
51f960f7c2 Remove print() 2023-07-15 10:53:38 +03:00
0cbed05d68 Move plugins loader to core. 2023-07-15 10:52:58 +03:00
c6c6ec31b0 Add new stock events;
Add async support to call_event();
Add **kwargs t0 call_event();
Sends new data to events;
2023-07-15 10:52:25 +03:00
8feba0e085 Minor update 2023-07-15 09:17:52 +03:00
a5202edf83 Relocate open() in plugins 2023-07-15 02:17:00 +03:00
64ce662d04 Add methods in KuiToi class 2023-07-15 02:15:11 +03:00
08e4f0fcba Update TODOs 2023-07-14 23:11:03 +03:00
99f40eadb0 Add returns from ev.call_events 2023-07-14 22:29:37 +03:00
5a40ab8b05 Add TODOs to code. 2023-07-14 22:27:23 +03:00
4f688d7c02 Update LICENCE 2023-07-14 21:55:19 +03:00
c4fe201b86 Move class Client to self file. 2023-07-14 21:52:24 +03:00
35 changed files with 1254 additions and 623 deletions

View File

@@ -6,6 +6,6 @@ Permission is hereby granted, free of charge, to any person obtaining a copy of
Permission is granted to sell and/ or distribute copies of the Software in a commercial context, subject to the following conditions: Permission is granted to sell and/ or distribute copies of the Software in a commercial context, subject to the following conditions:
- Substantial changes: adding, removing, or modifying large parts, shall be developed in the Software. Reorganizing logic in the software does not warrant a substantial change. - Substantial changes: adding, removing, or modifying large parts, shall be developed in the Software. Reorganizing logic in the software does not warrant a substantial change and received permission from the owner.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -36,13 +36,16 @@ BeamingDrive Multiplayer (BeamMP) server compatible with BeamMP clients.
- [x] Log history (.1.log, .2.log, ...) - [x] Log history (.1.log, .2.log, ...)
- [x] Console: - [x] Console:
- [x] Tabulation - [x] Tabulation
- [ ] _(Deferred)_ Static text (bug) - [x] _~~(By design)~~_ Static text (bug)
- [x] Events System - [x] Events System
- [x] Call events - [x] Call events
- [x] Create custom events - [x] Create custom events
- [ ] Return from events - [x] Return from events
- [x] Async support
- [x] Plugins support - [x] Plugins support
- [ ] KuiToi class
- [x] Load Python plugins - [x] Load Python plugins
- [x] Async support
- [ ] Load Lua plugins (Original BeamMP compatibility) - [ ] Load Lua plugins (Original BeamMP compatibility)
- [x] MultiLanguage (i18n support) - [x] MultiLanguage (i18n support)
- [x] Core - [x] Core
@@ -53,7 +56,7 @@ BeamingDrive Multiplayer (BeamMP) server compatible with BeamMP clients.
- [x] Configure FastAPI logger - [x] Configure FastAPI logger
- [ ] Sync with event system - [ ] Sync with event system
- [ ] Add methods... - [ ] Add methods...
- [ ] [Documentation](docs/en/readme.md) - [ ] [Documentation](./docs/)
## Installation ## Installation
@@ -78,6 +81,6 @@ Copyright (c) 2023 SantaSpeen (Maxim Khomutov)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without limitation in the rights to use, copy, modify, merge, publish, and/ or distribute copies of the Software in an educational or personal context, subject to the following conditions: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without limitation in the rights to use, copy, modify, merge, publish, and/ or distribute copies of the Software in an educational or personal context, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
Permission is granted to sell and/ or distribute copies of the Software in a commercial context, subject to the following conditions: Permission is granted to sell and/ or distribute copies of the Software in a commercial context, subject to the following conditions:
- Substantial changes: adding, removing, or modifying large parts, shall be developed in the Software. Reorganizing logic in the software does not warrant a substantial change. - Substantial changes: adding, removing, or modifying large parts, shall be developed in the Software. Reorganizing logic in the software does not warrant a substantial change and received permission from the owner.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
``` ```

View File

@@ -1,15 +1,15 @@
{ {
"": "Basic phases", "": "Basic phases",
"hello": "Hello from KuiToi-Server!", "hello": "Greetings from KuiToi Server!",
"config_path": "Use {} for config.", "config_path": "Use {} to configure.",
"init_ok": "Initializing ready.", "init_ok": "Initialization complete.",
"start": "Server started!", "start": "Server started!",
"stop": "Goodbye!", "stop": "Server stopped!",
"": "Server auth", "": "Server auth",
"auth_need_key": "BEAM key needed for starting the server!", "auth_need_key": "A BeamMP key is required to start the server!",
"auth_empty_key": "Key is empty!", "auth_empty_key": "The BeamMP key is empty!",
"auth_cannot_open_browser": "Cannot open browser: {}", "auth_cannot_open_browser": "Failed to open browser: {}",
"auth_use_link": "Use this link: {}", "auth_use_link": "Use this link: {}",
"": "GUI phases", "": "GUI phases",
@@ -17,32 +17,32 @@
"GUI_no": "No", "GUI_no": "No",
"GUI_ok": "Ok", "GUI_ok": "Ok",
"GUI_cancel": "Cancel", "GUI_cancel": "Cancel",
"GUI_need_key_message": "BEAM key needed for starting the server!\nDo you need to open the web link to obtain the key?", "GUI_need_key_message": "A BeamMP key is required to start the server!\nDo you want to open the link in a browser to obtain the key?",
"GUI_enter_key_message": "Please type your key:", "GUI_enter_key_message": "Please enter the key:",
"GUI_cannot_open_browser": "Cannot open browser.\nUse this link: {}", "GUI_cannot_open_browser": "Failed to open browser.\nUse this link: {}",
"": "Web phases", "": "Web phases",
"web_start": "WebAPI running on {} (Press CTRL+C to quit)", "web_start": "WebAPI started at {} (Press CTRL+C to quit)",
"": "Command: man", "": "Command: man",
"man_message_man": "man - display the manual page for COMMAND.\nUsage: man COMMAND", "man_message_man": "man - Displays help page for COMMAND.\nUsage: man COMMAND",
"help_message_man": "Display the manual page for COMMAND.", "help_message_man": "Displays help page for COMMAND.",
"man_for": "Manual for command", "man_for": "Help page for",
"man_message_not_found": "man: Manual message not found.", "man_message_not_found": "man: Help page not found.",
"man_command_not_found": "man: command \"{}\" not found!", "man_command_not_found": "man: Command \"{}\" not found!",
"": "Command: help", "": "Command: help",
"man_message_help": "help - display names and brief descriptions of available commands.\nUsage: help [--raw]\nThe `help` command displays a list of all available commands along with a brief description of each command.", "man_message_help": "help - Displays the names and short descriptions of commands.\nUsage: help [--raw]\nThe `help` command displays a list of all available commands and a brief description of each command.",
"help_message_help": "Display names and brief descriptions of available commands", "help_message_help": "Displays the names and short descriptions of commands.",
"help_command": "Command", "help_command": "Command",
"help_message": "Help message", "help_message": "Description",
"help_message_not_found": "No help message found", "help_message_not_found": "No description available.",
"": "Command: stop", "": "Command: stop",
"man_message_stop": "stop - Just shutting down the server.\nUsage: stop", "man_message_stop": "stop - Stops the server.\nUsage: stop",
"help_message_stop": "Server shutdown.", "help_message_stop": "Stops the server.",
"": "Command: exit", "": "Command: exit",
"man_message_exit": "exit - Just shutting down the server.\nUsage: stop", "man_message_exit": "exit - Stops the server.\nUsage: exit",
"help_message_exit": "Server shutdown." "help_message_exit": "Stops the server."
} }

View File

@@ -0,0 +1,4 @@
# MultiLanguage - i18n Support
In [example.json](./example.json) you will find a copy of [src/modules/i18n/files/ru.json](../../../src/modules/i18n/files/ru.json).\
If you want to translate to a language that has not been translated before or update an existing translation, I would be happy to receive your pull requests.

View File

@@ -0,0 +1,37 @@
import json
try:
import KuiToi
except ImportError:
pass
kt = KuiToi("Example")
log = kt.log
config = {"config_version": 0.1, "sql": {"enabled": False, "host": "127.0.0.1", "port": 3363, "database": "fucklua"}}
cfg_file = "config.json"
async def my_event_handler(event_data):
log.info(f"{event_data}")
async def load():
# Инициализация плагина
with open(cfg_file, 'w') as f:
json.dump(config, f)
cgf = config
log.info(cgf)
ev.register_event("my_event", my_event_handler)
log.info("Плагин загружен успешно.")
async def start():
# Запуск процессов плагина
await ev.call_async_event("my_event")
await ev.call_async_event("my_event", "Some data", data="some data too")
log.info("Плагин запустился успешно.")
async def unload():
# Код завершающий все процессы
log.info("Плагин выгружен успешно.")

View File

@@ -1,36 +1,37 @@
import KuiToi # Import server object import json
beam = KuiToi("TestPlugin") # Init plugin with name "TestPlugin" try:
log = beam.log # Use logger from server import KuiToi
except ImportError:
pass
kt = KuiToi("Example")
log = kt.log
config = {"config_version": 0.1, "sql": {"enabled": False, "host": "127.0.0.1", "port": 3363, "database": "fucklua"}}
cfg_file = "config.json"
def on_load(): def my_event_handler(event_data):
# When plugin initialization Server uses plugin.load() to load plugin. log.info(f"{event_data}")
# def load(): is really needed
log.info(beam.name)
# Events handlers def load():
# Инициализация плагина
def on_started(): with open(cfg_file, 'w') as f:
# Simple event handler json.dump(config, f)
log.info("Server starting...") cgf = config
log.info(cgf)
ev.register_event("my_event", my_event_handler)
log.info("Плагин загружен успешно.")
# Simple event register def start():
beam.register_event("on_started", on_started) # Запуск процессов плагина
ev.call_event("my_event")
ev.call_event("my_event", "Some data", data="some data too")
log.info("Плагин запустился успешно.")
def any_func(data=None): def unload():
# Custom event handler # Код завершающий все процессы
log.info(f"Data from any_func: {data}") log.info("Плагин выгружен успешно.")
# Create custom event
beam.register_event("my_event", any_func)
# Call custom event
beam.call_event("my_event")
beam.call_event("my_event", "Some data")
# This will be an error since any_func accepts only one argument at the input
beam.call_event("my_event", "Some data", "Some data1")

View File

@@ -1,32 +1,92 @@
# Plugins System # Plugin System
## Install ## Installing the Library with "Stubs"
###### (Lib can't ready to use) ###### (This means that it will not work without a server, but the IDE will suggest the API)
###### (The library is still under development)
* From pip:\ * Using pip:\
`$ pip install KuiToi` `$ pip install KuiToi`
* From source:\ * From source code:\
`git clone https://github.com/KuiToi/KuiToi-PyLib` `git clone https://github.com/KuiToi/KuiToi-PyLib`
## Example ## Example
```python ```python
import KuiToi try:
import KuiToi
except ImportError:
pass
beam = KuiToi("TestPlugin") kt = KuiToi("Example")
logger = beam.log log = kt.log
def load(): # Plugins load from here def my_event_handler(event_data):
print(beam.name) log.info(f"{event_data}")
def on_started(): def load():
logger.info("Server starting...") # Plugin initialization
ev.register_event("my_event", my_event_handler)
log.info("Plugin loaded successfully.")
beam.register_event("on_started", on_started)
def start():
# Running plugin processes
ev.call_event("my_event")
ev.call_event("my_event", "Some data", data="some data too")
log.info("Plugin started successfully.")
def unload():
# Code that ends all processes
log.info("Plugin unloaded successfully.")
``` ```
* Basic Events: ['on_started', 'on_auth, 'on_stop'] * It is recommended to use `open()` after `load()`. Otherwise, use `kt.load()` - creates a file in the `plugin/<plugin_name>/<filename>` folder.
* Create new event : `beam.register_event("my_event", my_event_function)` * Creating your own event: `kt.register_event("my_event", my_event_function)`
* Call event: `beam.call_event("my_event")` * Calling an event: `kt.call_event("my_event")`
* Call event with some data: `beam.call_event("my_event", data, data2)` * Calling an event with data: `kt.call_event("my_event", data, data2=data2)`
* Calls _**can't support**_ like this: `beam.call_event("my_event", data=data)` * Basic events: _Will write later_
## Async Functions
Async support is available.
```python
try:
import KuiToi
except ImportError:
pass
kt = KuiToi("Example")
log = kt.log
async def my_event_handler(event_data):
log.info(f"{event_data}")
async def load():
# Plugin initialization
ev.register_event("my_event", my_event_handler)
log.info("Plugin loaded successfully.")
async def start():
# Running plugin processes
await ev.call_async_event("my_event")
await ev.call_async_event("my_event", "Some data", data="some data too")
log.info("Plugin started successfully.")
async def unload():
# Code that ends all processes
log.info("Plugin unloaded successfully.")
```
A more extensive example can also be found in [async_example.py](./async_example.py).
* Creating your own event: `kt.register_event("my_event", my_event_function)` (register_event checks for function)
* 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)`
* Basic async events: _Will write later_

View File

@@ -1,9 +1,9 @@
# Documentation for KuiToi Server # Documentation for KuiToi Server
#### The documentation has not been perfected yet, but one day it will definitely happen ### The documentation is not perfect yet, but it will be one day
1. Setup and Start server - [here](setup) 1. Setup and Start server - [here](setup)
2. Plugins and Events system - [here](plugins) 2. Plugins and Events system - [here](plugins)
3. MultiLanguage - [here](./multilanguage) 3. MultiLanguage - [here](./multilanguage)
4. RESP API - [here](./web) 4. KuiToi WebAPI - [here](./web)
5. Something new 5. Something new...

View File

@@ -1,18 +1,32 @@
# Hello from KuiToi Server # Greetings from KuiToi Server
## Start ## Well, let's begin
* Need **Python 3.10.x** to start! ###### _(Here are the commands for Linux)_
* After cloning use this:
* **Python 3.10.x** is required to run the server! It won't work on Python 3.11...
* You can check the version of your Python installation with the following command:
```bash ```bash
$ python3 --version # Python 3.10.6 python3 --version # Python 3.10.6
$ python3 main.py --help # Show help message ```
$ python3 main.py # Start server * Clone the repository and navigate to it.
* Install everything that's needed.
* Then, using my "script", remove all unnecessary files and move to the core source code.
```bash
git clone -b Stable https://github.com/kuitoi/KuiToi-Server.git && cd KuiToi-Server
pip install -r requirements.txt
mv ./src/ $HOME/ktsrc/ && rm -rf ./* && mv $HOME/ktsrc/* . && rm -rf $HOME/ktsrc
```
* Here's how to view information about the server and start it:
```bash
python3 main.py --help # Displays all available commands
python3 main.py # Starts the server
``` ```
## Setup ## Configuration
* After starting server creating `kuitoi.yaml`; Default: * After starting the server, a `kuitoi.yaml` file will be created.
* By default, it looks like this:
```yaml ```yaml
!!python/object:modules.ConfigProvider.config_provider.Config !!python/object:modules.ConfigProvider.config_provider.Config
Auth: Auth:
@@ -23,11 +37,39 @@ Game:
max_cars: 1 max_cars: 1
players: 8 players: 8
Server: Server:
debug: true debug: false
description: This server uses KuiToi! description: Welcome to KuiToi Server!
language: en
name: KuiToi-Server name: KuiToi-Server
server_ip: 0.0.0.0 server_ip: 0.0.0.0
server_port: 30814 server_port: 30813
``` WebAPI:
* Server can't start without BEAM Auth.key enabled: false
secret_key: <random_key>
server_ip: 127.0.0.1
server_port: 8433
```
### Auth
* If you set `private: false` and do not set a `key`, the server will request a BeamMP key and will not start without it.
* By entering a BeamMP key, the server will appear in the launcher list.
* You can get a key here: [https://beammp.com/k/keys ↗](https://beammp.com/k/keys)
### Game
* `map` specifies only the name of the map. That is, open the mod with the map in `map.zip/levels` - the name of the map will be there, and that's what you need to insert.
* `max_cars` - the maximum number of cars per player
* `players` - the maximum number of players
### Server
* `debug` - should debug messages be displayed (for experienced users only; slightly affects performance)
* `description` - server description for the BeamMP launcher
* `language` - the language in which the server will run (currently available: en, ru)
* `name` - server name for the BeamMP launcher
* `server_ip` - the IP address to be used by the server (for experienced users only; defaults to 0.0.0.0)
* `server_port` - the port on which the server will run
### WebAPI
##### _Docs are not ready yet_

View File

@@ -1,3 +1,15 @@
# Web RESP API for the Server Here's the translation of the readme.txt content:
In development... # WebAPI for the server
## Available endpoints
* `/stop`:
* Required parameters:
* `secret_key` - The key specified in the server configuration
* `/event.get`
* The endpoint is not yet ready
* Required parameters:
* `secret_key` - The key specified in the server configuration

View File

@@ -0,0 +1,4 @@
# MultiLanguage - Поддержка i18n
В [example.json](./example.json) это копия [src/modules/i18n/files/ru.json](../../../src/modules/i18n/files/ru.json)\
Если есть желание перевести на не переведённый ранее язык, или обновить уже существующий перевод буду рад вашим пул реквестам.

View File

@@ -0,0 +1,37 @@
import json
try:
import KuiToi
except ImportError:
pass
kt = KuiToi("Example")
log = kt.log
config = {"config_version": 0.1, "sql": {"enabled": False, "host": "127.0.0.1", "port": 3363, "database": "fucklua"}}
cfg_file = "config.json"
async def my_event_handler(event_data):
log.info(f"{event_data}")
async def load():
# Инициализация плагина
with open(cfg_file, 'w') as f:
json.dump(config, f)
cgf = config
log.info(cgf)
ev.register_event("my_event", my_event_handler)
log.info("Плагин загружен успешно.")
async def start():
# Запуск процессов плагина
await ev.call_async_event("my_event")
await ev.call_async_event("my_event", "Some data", data="some data too")
log.info("Плагин запустился успешно.")
async def unload():
# Код завершающий все процессы
log.info("Плагин выгружен успешно.")

View File

@@ -1,36 +1,37 @@
import KuiToi # Import server object import json
beam = KuiToi("TestPlugin") # Init plugin with name "TestPlugin" try:
log = beam.log # Use logger from server import KuiToi
except ImportError:
pass
kt = KuiToi("Example")
log = kt.log
config = {"config_version": 0.1, "sql": {"enabled": False, "host": "127.0.0.1", "port": 3363, "database": "fucklua"}}
cfg_file = "config.json"
def on_load(): def my_event_handler(event_data):
# When plugin initialization Server uses plugin.load() to load plugin. log.info(f"{event_data}")
# def load(): is really needed
log.info(beam.name)
# Events handlers def load():
# Инициализация плагина
def on_started(): with open(cfg_file, 'w') as f:
# Simple event handler json.dump(config, f)
log.info("Server starting...") cgf = config
log.info(cgf)
ev.register_event("my_event", my_event_handler)
log.info("Плагин загружен успешно.")
# Simple event register def start():
beam.register_event("on_started", on_started) # Запуск процессов плагина
ev.call_event("my_event")
ev.call_event("my_event", "Some data", data="some data too")
log.info("Плагин запустился успешно.")
def any_func(data=None): def unload():
# Custom event handler # Код завершающий все процессы
log.info(f"Data from any_func: {data}") log.info("Плагин выгружен успешно.")
# Create custom event
beam.register_event("my_event", any_func)
# Call custom event
beam.call_event("my_event")
beam.call_event("my_event", "Some data")
# This will be an error since any_func accepts only one argument at the input
beam.call_event("my_event", "Some data", "Some data1")

View File

@@ -12,24 +12,81 @@
## Пример ## Пример
```python ```python
import KuiToi try:
import KuiToi
except ImportError:
pass
beam = KuiToi("TestPlugin") kt = KuiToi("Example")
logger = beam.log log = kt.log
def load(): # Plugins load from here def my_event_handler(event_data):
print(beam.name) log.info(f"{event_data}")
def on_started(): def load():
logger.info("Server starting...") # Инициализация плагина
ev.register_event("my_event", my_event_handler)
log.info("Плагин загружен успешно.")
beam.register_event("on_started", on_started)
def start():
# Запуск процессов плагина
ev.call_event("my_event")
ev.call_event("my_event", "Some data", data="some data too")
log.info("Плагин запустился успешно.")
def unload():
# Код завершающий все процессы
log.info("Плагин выгружен успешно.")
``` ```
Так же более обширный пример можно найти в [example.py](./example.py) * Рекомендуется использовать `open()` после `load()`, иначе стоит использовать `kt.load()` - Создаёт файл в папке `plugin/<plugin_name>/<filename>`
* Создание своего ивента : `kt.register_event("my_event", my_event_function)` -
* Вызов ивента: `kt.call_event("my_event")`
* Вызов ивента с данными: `kt.call_event("my_event", data, data2=data2)`
* Базовые ивенты: озже напишу_
* Базовые ивенты: ['on_started', 'on_auth, 'on_stop'] ## Async функции
* Создание своего ивента : `beam.register_event("my_event", my_event_function)`
* Вызов ивента: `beam.call_event("my_event")` Поддержка async есть
* Вызов ивента с данными: `beam.call_event("my_event", data, data2)`
* Вызовы с указанием переменой _**не поддерживаются**_: `beam.call_event("my_event", data=data)` ```python
try:
import KuiToi
except ImportError:
pass
kt = KuiToi("Example")
log = kt.log
async def my_event_handler(event_data):
log.info(f"{event_data}")
async def load():
# Инициализация плагина
ev.register_event("my_event", my_event_handler)
log.info("Плагин загружен успешно.")
async def start():
# Запуск процессов плагина
await ev.call_async_event("my_event")
await ev.call_async_event("my_event", "Some data", data="some data too")
log.info("Плагин запустился успешно.")
async def unload():
# Код завершающий все процессы
log.info("Плагин выгружен успешно.")
```
Так же более обширный пример можно найти в [async_example.py](./async_example.py)
* Создание своего ивента: `kt.register_event("my_event", my_event_function)` (в register_event стоит проверка на функцию)
* Вызов async ивента: `kt.call_async_event("my_event")`
* Вызов async ивента: `kt.call_async_event("my_event", data, data2=data2)`
* Базовые async ивенты: озже напишу_

View File

@@ -5,5 +5,5 @@
1. Настройка и Запуск сервера - [тута](./setup) 1. Настройка и Запуск сервера - [тута](./setup)
2. Плагины и Ивент система - [тута](./plugins) 2. Плагины и Ивент система - [тута](./plugins)
3. Мультиязычность - [тута](./multilanguage) 3. Мультиязычность - [тута](./multilanguage)
4. RESP API - [тута](./web) 4. KuiToi WebAPI - [тута](./web)
5. Тут будет что-то ново.... 5. Тут будет что-то ново....

View File

@@ -38,12 +38,39 @@ Game:
players: 8 players: 8
Server: Server:
debug: false debug: false
description: This server uses KuiToi! description: Welcome to KuiToi Server!
language: en
name: KuiToi-Server name: KuiToi-Server
server_ip: 0.0.0.0 server_ip: 0.0.0.0
server_port: 30814 server_port: 30813
WebAPI:
enabled: false
secret_key: <random_key>
server_ip: 127.0.0.1
server_port: 8433
``` ```
### Auth
* Если поставить `private: false` и не установить `key`, то сервер запросит BeamMP ключ, без него не запустится. * Если поставить `private: false` и не установить `key`, то сервер запросит BeamMP ключ, без него не запустится.
* Введя BeamMP ключ сервер появится в списке лаунчера. * Введя BeamMP ключ сервер появится в списке лаунчера.
* Взять ключ можно тут: [https://beammp.com/k/keys](https://beammp.com/k/keys) * Взять ключ можно тут: [https://beammp.com/k/keys](https://beammp.com/k/keys)
### Game
* `map` указывается только название карты, т.е. открываем мод с картой в `map.zip/levels` - вот тут будет название карты, его мы и вставляем
* `max_cars` - Максимальное количество машин на игрока
* `players` - Максимально количество игроков
### Server
* `debug` - Нужно ли выводить debug сообщения (только для опытных пользователей, немного теряется в производительности)
* `description` - Описания сервера для лаунчера BeamMP
* `language` - С каким языком запустится сервер (Доступные на данный момент: en, ru)
* `name` - Названия сервер для лаунчера BeamMP
* `server_ip` - Какой IP адрес занять серверу (только для опытных пользователей, по умолчанию 0.0.0.0)
* `server_port` - На каком порту будет работать сервер
### WebAPI
##### _Доки не готовы_

View File

@@ -1,3 +1,14 @@
# Web RESP API для сервера # WebAPI для сервера
## Доступные endpoints
* `/stop`:
* Необходимые парамеры:
* `secret_key` - Ключ, который указан в конфигурации сервера
* `/event.get`
* Точка не готова
* Необходимые парамеры:
* `secret_key` - Ключ, который указан в конфигурации сервера
В разработке

360
src/core/Client.py Normal file
View File

@@ -0,0 +1,360 @@
# Developed by KuiToi Dev
# File core.tcp_server.py
# Written by: SantaSpeen
# Core version: 0.2.3
# Licence: FPA
# (c) kuitoi.su 2023
import asyncio
import math
import zlib
from core import utils
class Client:
def __init__(self, reader, writer, core):
self.__reader = reader
self.__writer = writer
self._down_rw = (None, None)
self.__Core = core
self.__alive = True
self._loop = asyncio.get_event_loop()
self._log = utils.get_logger("client(None:0)")
self._addr = writer.get_extra_info("sockname")
self._cid = -1
self._key = None
self.nick = None
self.roles = None
self._guest = True
self._ready = False
self._cars = []
@property
def _writer(self):
return self.__writer
@property
def log(self):
return self._log
@property
def addr(self):
return self._addr
@property
def cid(self):
return self._cid
@property
def key(self):
return self._key
@property
def guest(self):
return self._guest
@property
def ready(self):
return self._ready
@property
def cars(self):
return self.cars
def _update_logger(self):
self._log = utils.get_logger(f"{self.nick}:{self.cid}")
self.log.debug(f"Update logger")
def is_disconnected(self):
if not self.__alive:
return True
res = self.__writer.is_closing()
if res:
self.log.debug(f"Disconnected.")
self.__alive = False
return True
else:
self.log.debug(f"Alive.")
self.__alive = True
return False
async def kick(self, reason):
if not self.__alive:
self.log.debug(f"{self.nick}.kick('{reason}') skipped: Not alive;")
return
# TODO: i18n
self.log.info(f"Kicked with reason: \"{reason}\"")
await self._send(b"K" + bytes(reason, "utf-8"))
self.__alive = False
async def _send(self, data, to_all=False, to_self=True, to_udp=False, writer=None):
# TNetwork.cpp; Line: 383
# BeamMP TCP protocol sends a header of 4 bytes, followed by the data.
# [][][][][][]...[]
# ^------^^---...-^
# size data
if type(data) == str:
data = bytes(data, "utf-8")
if writer is None:
writer = self.__writer
if to_all:
code = chr(data[0])
for client in self.__Core.clients:
if not client or (client is self and not to_self):
continue
if not to_udp or code in ['V', 'W', 'Y', 'E']:
if code in ['O', 'T'] or len(data) > 1000:
# TODO: Compress data
await client._send(data)
else:
await client._send(data)
else:
# TODO: UDP send
self.log.debug(f"UDP Part not ready: {code}")
return
header = len(data).to_bytes(4, "little", signed=True)
self.log.debug(f'len: {len(data)}; send: {header + data!r}')
try:
writer.write(header + data)
await writer.drain()
except ConnectionError:
self.log.debug('tcp_send: Disconnected')
self.__alive = False
async def _recv(self):
try:
header = await self.__reader.read(4)
int_header = 0
for i in range(len(header)):
int_header += header[i]
if int_header <= 0:
await asyncio.sleep(0.1)
self.is_disconnected()
if self.__alive:
self.log.debug(f"Header: {header}")
await self.kick("Invalid packet - header negative")
return b""
if int_header > 100 * MB:
await self.kick("Header size limit exceeded")
self.log.warn(f"Client {self.nick}:{self.cid} sent header of >100MB - "
f"assuming malicious intent and disconnecting the client.")
return b""
data = await self.__reader.read(100 * MB)
self.log.debug(f"header: `{header}`; int_header: `{int_header}`; data: `{data}`;")
if len(data) != int_header:
self.log.debug(f"WARN Expected to read {int_header} bytes, instead got {len(data)}")
abg = b"ABG:"
if len(data) > len(abg) and data.startswith(abg):
data = zlib.decompress(data[len(abg):])
self.log.debug(f"ABG: {data}")
return data
return data
except ConnectionError:
self.__alive = False
return b""
async def _split_load(self, start, end, d_sock, filename):
# TODO: Speed limiter
real_size = end - start
writer = self._down_rw[1] if d_sock else self.__writer
who = 'dwn' if d_sock else 'srv'
if config.Server["debug"]:
self.log.debug(f"[{who}] Real size: {real_size / MB}mb; {real_size == end}, {real_size * 2 == end}")
with open(filename, 'rb') as f:
f.seek(start)
data = f.read(end)
try:
writer.write(data)
await writer.drain()
self.log.debug(f"[{who}] File sent.")
except ConnectionError:
self.__alive = False
self.log.debug(f"[{who}] Disconnected.")
return real_size
async def _sync_resources(self):
while self.__alive:
data = await self._recv()
self.log.debug(f"data: {data!r}")
if data.startswith(b"f"):
file = data[1:].decode("utf-8")
# TODO: i18n
self.log.info(f"Requested mode: {file!r}")
size = -1
for mod in self.__Core.mods_list:
if type(mod) == int:
continue
if mod.get('path') == file:
size = mod['size']
self.log.debug("File is accept.")
break
self.log.debug(f"Mode size: {size}")
if size == -1:
await self._send(b"CO")
await self.kick(f"Not allowed mod: " + file)
return
await self._send(b"AG")
t = 0
while not self._down_rw[0]:
await asyncio.sleep(0.1)
t += 1
if t > 50:
await self.kick("Missing download socket")
return
half_size = math.floor(size / 2)
uploads = [
self._split_load(0, half_size, False, file),
self._split_load(half_size, size, True, file)
]
sl0, sl1 = await asyncio.gather(*uploads)
sent = sl0 + sl1
ok = sent == size
lost = size - sent
self.log.debug(f"SplitLoad_0: {sl0}; SplitLoad_1: {sl1}; At all ({ok}): Sent: {sent}; Lost: {lost}")
if not ok:
self.__alive = False
# TODO: i18n
self.log.error(f"Error while sending.")
return
elif data.startswith(b"SR"):
path_list = ''
size_list = ''
for mod in self.__Core.mods_list:
if type(mod) == int:
continue
path_list += f"{mod['path']};"
size_list += f"{mod['size']};"
mod_list = path_list + size_list
self.log.debug(f"Mods List: {mod_list}")
if len(mod_list) == 0:
await self._send(b"-")
else:
await self._send(bytes(mod_list, "utf-8"))
elif data == b"Done":
await self._send(b"M/levels/" + bytes(config.Game['map'], 'utf-8') + b"/info.json")
break
return
async def _looper(self):
await self._send(b"P" + bytes(f"{self.cid}", "utf-8")) # Send clientID
await self._sync_resources()
while self.__alive:
data = await self._recv()
if not data:
self.__alive = False
break
# V to Y
if 89 >= data[0] >= 86:
await self._send(data, to_all=True, to_self=False)
code = chr(data[0])
self.log.debug(f"Received code: {code}, data: {data}")
match code:
case "H":
# Client connected
ev.call_event("player_join", player=self)
await ev.call_async_event("player_join", player=self)
await self._send(f"Sn{self.nick}", to_all=True) # I don't know for what it
await self._send(f"JWelcome {self.nick}!", to_all=True) # Hello message
self._ready = True
# TODO: Sync cars
# for client in self.__Core.clients:
# for car in client.cars:
# await self._tcp_send(car)
case "C":
# Chat
msg = data.decode()[4 + len(self.nick):]
if not msg:
self.log.debug("Tried to send an empty event, ignoring")
continue
self.log.info(f"Received message: {msg}")
# TODO: Handle chat event
to_ev = {"message": msg, "player": self}
ev_data_list = ev.call_event("chat_receive", **to_ev)
d2 = await ev.call_async_event("chat_receive", **to_ev)
ev_data_list.extend(d2)
need_send = True
for ev_data in ev_data_list:
try:
message = ev_data["message"]
to_all = ev_data.get("to_all")
if to_all is None:
if need_send:
need_send = False
to_all = True
if to_all:
if need_send:
need_send = False
to_self = ev_data.get("to_self")
if to_self is None:
to_self = True
to_client = ev_data.get("to_client")
writer = None
if to_client:
writer = to_client._writer
await self._send(f"C:{message}", to_all=to_all, to_self=to_self, writer=writer)
except KeyError | AttributeError:
self.log.error(f"Returns invalid data: {ev_data}")
if need_send:
await self._send(data, to_all=True)
case "O":
# TODO: ParseVehicle
pass
case "E":
# TODO: HandleEvent
pass
case "N":
# TODO: N
pass
case _:
pass
async def _remove_me(self):
await asyncio.sleep(0.3)
self.__alive = False
if (self.cid > 0 or self.nick is not None) and \
self.__Core.clients_by_nick.get(self.nick):
# if self.ready:
# await self.tcp_send(b"", to_all=True) # I'm disconnected.
self.log.debug(f"Removing client {self.nick}:{self.cid}")
# TODO: i18n
self.log.info("Disconnected")
self.__Core.clients[self.cid] = None
self.__Core.clients_by_id.pop(self.cid)
self.__Core.clients_by_nick.pop(self.nick)
else:
self.log.debug(f"Removing client; Closing connection...")
try:
if not self.__writer.is_closing():
self.__writer.close()
except Exception as e:
self.log.debug(f"Error while closing writer: {e}")
try:
_, down_w = self._down_rw
if down_w and not down_w.is_closing():
down_w.close()
except Exception as e:
self.log.debug(f"Error while closing download writer: {e}")

54
src/core/Client.pyi Normal file
View File

@@ -0,0 +1,54 @@
# Developed by KuiToi Dev
# File core.tcp_server.py
# Written by: SantaSpeen
# Core version: 0.2.3
# Licence: FPA
# (c) kuitoi.su 2023
import asyncio
from asyncio import StreamReader, StreamWriter
from logging import Logger
from typing import Tuple
from core import Core, utils
class Client:
def __init__(self, reader: StreamReader, writer: StreamWriter, core: Core) -> "Client":
self.__reader = reader
self.__writer = writer
self._down_rw: Tuple[StreamReader, StreamWriter] | Tuple[None, None] = (None, None)
self._log = utils.get_logger("client(id: )")
self._addr = writer.get_extra_info("sockname")
self._loop = asyncio.get_event_loop()
self.__Core = core
self._cid: int = -1
self._key: str = None
self.nick: str = None
self.roles: str = None
self._guest = True
self.__alive = True
self._ready = False
@property
def _writer(self) -> StreamWriter: ...
@property
def log(self) -> Logger: ...
@property
def addr(self) -> Tuple[str, int]: ...
@property
def cid(self) -> int: ...
@property
def key(self) -> str: ...
@property
def guest(self) -> bool: ...
@property
def ready(self) -> bool: ...
def is_disconnected(self) -> bool: ...
async def kick(self, reason: str) -> None: ...
async def _send(self, data: bytes | str, to_all: bool = False, to_self: bool = True, to_udp: bool = False, writer: StreamWriter = None) -> None: ...
async def _sync_resources(self) -> None: ...
async def _recv(self) -> bytes: ...
async def _split_load(self, start: int, end: int, d_sock: bool, filename: str) -> None: ...
async def _looper(self) -> None: ...
def _update_logger(self) -> None: ...
async def _remove_me(self) -> None: ...

View File

@@ -2,7 +2,7 @@
# File core.__init__.py # File core.__init__.py
# Written by: SantaSpeen # Written by: SantaSpeen
# Version 1.3 # Version 1.3
# Core version: 0.2.2 # Core version: 0.2.3
# Licence: FPA # Licence: FPA
# (c) kuitoi.su 2023 # (c) kuitoi.su 2023
# Special thanks to: AI Sage(https://poe.com/Sage), AI falcon-40b-v7(https://OpenBuddy.ai) # Special thanks to: AI Sage(https://poe.com/Sage), AI falcon-40b-v7(https://OpenBuddy.ai)
@@ -10,8 +10,8 @@
__title__ = 'KuiToi-Server' __title__ = 'KuiToi-Server'
__description__ = 'BeamingDrive Multiplayer server compatible with BeamMP clients.' __description__ = 'BeamingDrive Multiplayer server compatible with BeamMP clients.'
__url__ = 'https://github.com/kuitoi/kuitoi-Server' __url__ = 'https://github.com/kuitoi/kuitoi-Server'
__version__ = '0.2.2' __version__ = '0.2.3'
__build__ = 1113 # Я это считаю лог файлами __build__ = 1208 # Я это считаю лог файлами
__author__ = 'SantaSpeen' __author__ = 'SantaSpeen'
__author_email__ = 'admin@kuitoi.su' __author_email__ = 'admin@kuitoi.su'
__license__ = "FPA" __license__ = "FPA"
@@ -19,7 +19,6 @@ __copyright__ = 'Copyright 2023 © SantaSpeen (Maxim Khomutov)'
import asyncio import asyncio
import builtins import builtins
import os
import webbrowser import webbrowser
import prompt_toolkit.shortcuts as shortcuts import prompt_toolkit.shortcuts as shortcuts
@@ -27,7 +26,7 @@ import prompt_toolkit.shortcuts as shortcuts
from .utils import get_logger from .utils import get_logger
from core.core import Core from core.core import Core
from main import parser from main import parser
from modules import ConfigProvider, EventsSystem, PluginsLoader from modules import ConfigProvider, EventsSystem
from modules import Console from modules import Console
from modules import MultiLanguage from modules import MultiLanguage
@@ -107,16 +106,8 @@ console.builtins_hook()
console.add_command("stop", console.stop, i18n.man_message_stop, i18n.help_message_stop) console.add_command("stop", console.stop, i18n.man_message_stop, i18n.help_message_stop)
console.add_command("exit", console.stop, i18n.man_message_exit, i18n.help_message_exit) console.add_command("exit", console.stop, i18n.man_message_exit, i18n.help_message_exit)
log.debug("Initializing PluginsLoader...")
if not os.path.exists("plugins"):
os.mkdir("plugins")
pl = PluginsLoader("plugins")
pl.load_plugins()
builtins.B = 1 builtins.B = 1
builtins.KB = B * 1024 builtins.KB = B * 1024
builtins.MB = KB * 1024 builtins.MB = KB * 1024
builtins.GB = MB * 1024 builtins.GB = MB * 1024
builtins.TB = GB * 1024 builtins.TB = GB * 1024
log.info(i18n.init_ok)

View File

@@ -1,300 +1,25 @@
# Developed by KuiToi Dev # Developed by KuiToi Dev
# File core.core.py # File core.core.py
# Written by: SantaSpeen # Written by: SantaSpeen
# Version: 0.2.2 # Version: 0.2.3
# Licence: FPA # Licence: FPA
# (c) kuitoi.su 2023 # (c) kuitoi.su 2023
import asyncio import asyncio
import math
import os import os
import random import random
import zlib
from threading import Thread from threading import Thread
import aiohttp import aiohttp
import uvicorn import uvicorn
from core import utils from core import utils
from core.Client import Client
from core.tcp_server import TCPServer from core.tcp_server import TCPServer
from core.udp_server import UDPServer from core.udp_server import UDPServer
from modules import PluginsLoader
from modules.WebAPISystem import app as webapp from modules.WebAPISystem import app as webapp
class Client:
def __init__(self, reader, writer, core):
self.reader = reader
self.writer = writer
self.down_rw = (None, None)
self.log = utils.get_logger("client(None:0)")
self.addr = writer.get_extra_info("sockname")
self.loop = asyncio.get_event_loop()
self.Core = core
self.cid = -1
self.key = None
self.nick = None
self.roles = None
self.guest = True
self.alive = True
self.ready = False
def _update_logger(self):
self.log = utils.get_logger(f"{self.nick}:{self.cid})")
self.log.debug(f"Update logger")
def is_disconnected(self):
if not self.alive:
return True
res = self.writer.is_closing()
if res:
self.log.debug(f"Client Disconnected")
self.alive = False
return True
else:
self.log.debug(f"Client Alive")
self.alive = True
return False
async def kick(self, reason):
if not self.alive:
self.log.debug(f"Kick({reason}) skipped;")
return
self.log.info(f"Kicked with reason: \"{reason}\"")
await self.tcp_send(b"K" + bytes(reason, "utf-8"))
self.alive = False
# await self.remove_me()
async def tcp_send(self, data, to_all=False, writer=None):
# TNetwork.cpp; Line: 383
# BeamMP TCP protocol sends a header of 4 bytes, followed by the data.
# [][][][][][]...[]
# ^------^^---...-^
# size data
if writer is None:
writer = self.writer
if to_all:
for client in self.Core.clients:
if not client:
continue
await client.tcp_send(data)
return
# self.log.debug(f"tcp_send({data})")
if len(data) == 10:
data += b"."
header = len(data).to_bytes(4, "little", signed=True)
self.log.debug(f'len: {len(data)}; send: {header + data}')
try:
writer.write(header + data)
await writer.drain()
except ConnectionError:
self.log.debug('tcp_send: Disconnected')
self.alive = False
async def recv(self):
try:
header = await self.reader.read(4) # header: 4 bytes
int_header = 0
for i in range(len(header)):
int_header += header[i]
if int_header <= 0:
await asyncio.sleep(0.1)
self.is_disconnected()
if self.alive:
self.log.debug(f"Header: {header}")
await self.kick("Invalid packet - header negative")
return b""
if int_header > 100 * MB:
await self.kick("Header size limit exceeded")
self.log.warn(f"Client {self.nick}:{self.cid} sent header of >100MB - "
f"assuming malicious intent and disconnecting the client.")
return b""
data = await self.reader.read(100 * MB)
self.log.debug(f"header: `{header}`; int_header: `{int_header}`; data: `{data}`;")
if len(data) != int_header:
self.log.debug(f"WARN Expected to read {int_header} bytes, instead got {len(data)}")
abg = b"ABG:"
if len(data) > len(abg) and data.startswith(abg):
data = zlib.decompress(data[len(abg):])
self.log.debug(f"ABG: {data}")
return data
return data
except ConnectionError:
self.alive = False
return b""
async def _split_load(self, start, end, d_sock, filename):
real_size = end - start
writer = self.down_rw[1] if d_sock else self.writer
who = 'dwn' if d_sock else 'srv'
self.log.debug(f"[{who}] Real size: {real_size/MB}mb; {real_size == end}, {real_size*2 == end}")
with open(filename, 'rb') as f:
f.seek(start)
data = f.read(end)
try:
writer.write(data)
await writer.drain()
self.log.debug(f"[{who}] File sent.")
except ConnectionError:
self.alive = False
self.log.debug(f"[{who}] Disconnected.")
# break
return real_size
# chunk_size = 125 * MB
# if chunk_size > real_size:
# chunk_size = real_size
# chunks = math.floor(real_size / chunk_size)
# self.log.debug(f"[{who}] s:{start}, e:{end}, c:{chunks}, cz:{chunk_size/MB}mb, rs:{real_size/MB}mb")
# dw = 0
# for chunk in range(1, chunks + 1):
# chunk_end = start + (chunk_size * chunk)
# chunk_start = chunk_end - chunk_size
# # if chunk_start != 0:
# # chunk_start -= 1
# real_size -= chunk_size
# if chunk_size > real_size:
# chunk_end = real_size
# self.log.debug(f"[{who}] Chunk: {chunk}; Start: {chunk_start}; End: {chunk_end/MB};")
# with open(filename, 'rb') as f:
# f.seek(chunk_start)
# data = f.read(chunk_end)
# try:
# writer.write(data)
# await writer.drain()
# except ConnectionError:
# self.alive = False
# self.log.debug(f"[{who}] Disconnected")
# break
# dw += len(data)
# del data
# self.log.debug(f"[{who}] File sent.")
# return dw
async def sync_resources(self):
while self.alive:
data = await self.recv()
self.log.debug(f"data: {data!r}")
if data.startswith(b"f"):
file = data[1:].decode("utf-8")
self.log.debug(f"Sending File: {file}")
size = -1
for mod in self.Core.mods_list:
if type(mod) == int:
continue
if mod.get('path') == file:
size = mod['size']
self.log.debug("File is accept.")
break
if size == -1:
await self.tcp_send(b"CO")
await self.kick(f"Not allowed mod: " + file)
return
await self.tcp_send(b"AG")
t = 0
while not self.down_rw[0]:
await asyncio.sleep(0.1)
t += 1
if t > 50:
await self.kick("Missing download socket")
return
self.log.info(f"Requested mode: {file!r}")
self.log.debug(f"Mode size: {size/MB}")
msize = math.floor(size / 2)
# uploads = [
# asyncio.create_task(self._split_load(0, msize, False, file)), # SplitLoad_0
# asyncio.create_task(self._split_load(msize, size, True, file)) # SplitLoad_1
# ]
# await asyncio.wait(uploads)
uploads = [
self._split_load(0, msize, False, file),
self._split_load(msize, size, True, file)
]
sl0, sl1 = await asyncio.gather(*uploads)
sent = sl0 + sl1
ok = sent == size
lost = size - sent
self.log.debug(f"SplitLoad_0: {sl0}; SplitLoad_1: {sl1}; At all ({ok}): Sent: {sent}; Lost: {lost}")
self.log.debug(f"SplitLoad_0: {sl0/MB}mb; "
f"SplitLoad_1: {sl1/MB}MB; At all ({ok}): Sent: {sent/MB}mb; Lost: {lost/MB}mb")
if not ok:
self.alive = False
self.log.error(f"Error while sending.")
return
elif data.startswith(b"SR"):
path_list = ''
size_list = ''
for mod in self.Core.mods_list:
if type(mod) == int:
continue
path_list += f"{mod['path']};"
size_list += f"{mod['size']};"
mod_list = path_list + size_list
self.log.debug(f"Mods List: {mod_list}")
if len(mod_list) == 0:
await self.tcp_send(b"-")
else:
await self.tcp_send(bytes(mod_list, "utf-8"))
elif data == b"Done":
await self.tcp_send(b"M/levels/" + bytes(config.Game['map'], 'utf-8') + b"/info.json")
break
return
async def looper(self):
await self.tcp_send(b"P" + bytes(f"{self.cid}", "utf-8")) # Send clientID
await self.sync_resources()
while self.alive:
data = await self.recv()
if data == b"":
if not self.alive:
break
else:
await asyncio.sleep(.2)
self.is_disconnected()
continue
code = data.decode()[0]
self.log.debug(f"Received code: {code}, data: {data}")
match code:
case "H":
# Client connected
self.ready = True
await self.tcp_send(b"Sn" + bytes(self.nick, "utf-8"), to_all=True)
case "C":
# Chat
await self.tcp_send(data, to_all=True)
async def remove_me(self):
await asyncio.sleep(0.3)
self.alive = False
if (self.cid > 0 or self.nick is not None) and \
self.Core.clients_by_nick.get(self.nick):
# if self.ready:
# await self.tcp_send(b"", to_all=True) # I'm disconnected.
self.log.debug(f"Removing client {self.nick}:{self.cid}")
self.log.info("Disconnected")
self.Core.clients[self.cid] = None
self.Core.clients_by_id.pop(self.cid)
self.Core.clients_by_nick.pop(self.nick)
else:
self.log.debug(f"Removing client; Closing connection...")
if not self.writer.is_closing():
self.writer.close()
_, down_w = self.down_rw
if down_w and not down_w.is_closing():
down_w.close()
class Core: class Core:
def __init__(self): def __init__(self):
@@ -318,7 +43,11 @@ class Core:
self.client_major_version = "2.0" self.client_major_version = "2.0"
self.BeamMP_version = "3.2.0" self.BeamMP_version = "3.2.0"
def get_client(self, cid=None, nick=None): ev.register_event("get_player", self.get_client)
def get_client(self, cid=None, nick=None, from_ev=None):
if from_ev is not None:
return self.get_client(*from_ev['args'], **from_ev['kwargs'])
if cid is not None: if cid is not None:
return self.clients_by_id.get(cid) return self.clients_by_id.get(cid)
if nick: if nick:
@@ -336,7 +65,7 @@ class Core:
break break
await asyncio.sleep(random.randint(3, 9) * 0.01) await asyncio.sleep(random.randint(3, 9) * 0.01)
if not self.clients[cid]: if not self.clients[cid]:
client.cid = cid client._cid = cid
self.clients_by_nick.update({client.nick: client}) self.clients_by_nick.update({client.nick: client})
self.log.debug(f"Inserting client: {client.nick}:{client.cid}") self.log.debug(f"Inserting client: {client.nick}:{client.cid}")
self.clients_by_id.update({client.cid: client}) self.clients_by_id.update({client.cid: client})
@@ -356,7 +85,7 @@ class Core:
for client in self.clients: for client in self.clients:
if not client: if not client:
continue continue
out += f"{client.nick}" out += f"{client._nick}"
if need_cid: if need_cid:
out += f":{client.cid}" out += f":{client.cid}"
out += "," out += ","
@@ -375,7 +104,7 @@ class Core:
if not client.ready: if not client.ready:
client.is_disconnected() client.is_disconnected()
continue continue
await client.tcp_send(bytes(ca, "utf-8")) await client._send(bytes(ca, "utf-8"))
@staticmethod @staticmethod
def start_web(): def start_web():
@@ -397,6 +126,7 @@ class Core:
async def heartbeat(self, test=False): async def heartbeat(self, test=False):
if config.Auth["private"] or self.direct: if config.Auth["private"] or self.direct:
if test: if test:
# TODO: i18n
self.log.info(f"Server runnig in Direct connect mode.") self.log.info(f"Server runnig in Direct connect mode.")
self.direct = True self.direct = True
return return
@@ -447,6 +177,7 @@ class Core:
status = body.get("status") status = body.get("status")
msg = body.get("msg") msg = body.get("msg")
if status == "2000": if status == "2000":
# TODO: i18n
self.log.info(f"Authenticated! {msg}") self.log.info(f"Authenticated! {msg}")
elif status == "200": elif status == "200":
self.log.info(f"Resumed authenticated session. {msg}") self.log.info(f"Resumed authenticated session. {msg}")
@@ -462,6 +193,7 @@ class Core:
if not config.Auth['private']: if not config.Auth['private']:
raise KeyboardInterrupt raise KeyboardInterrupt
if test: if test:
# TODO: i18n
self.log.info(f"Server still runnig, but only in Direct connect mode.") self.log.info(f"Server still runnig, but only in Direct connect mode.")
if test: if test:
@@ -472,13 +204,19 @@ class Core:
self.log.error(f"Error in heartbeat: {e}") self.log.error(f"Error in heartbeat: {e}")
async def main(self): async def main(self):
self.run = True
self.tcp = self.tcp(self, self.server_ip, self.server_port) self.tcp = self.tcp(self, self.server_ip, self.server_port)
self.udp = self.udp(self, self.server_ip, self.server_port) self.udp = self.udp(self, self.server_ip, self.server_port)
console.add_command( console.add_command(
"list", "list",
lambda x: f"Players list: {self.get_clients_list(True)}" lambda x: f"Players list: {self.get_clients_list(True)}"
) )
self.log.debug("Initializing PluginsLoader...")
if not os.path.exists("plugins"):
os.mkdir("plugins")
pl = PluginsLoader("plugins")
await pl.load()
try: try:
# WebApi Start # WebApi Start
if config.WebAPI["enabled"]: if config.WebAPI["enabled"]:
@@ -502,40 +240,49 @@ class Core:
self.mods_list.append({"path": path, "size": size}) self.mods_list.append({"path": path, "size": size})
self.mods_list[0] += size self.mods_list[0] += size
self.log.debug(f"mods_list: {self.mods_list}") self.log.debug(f"mods_list: {self.mods_list}")
lmods = len(self.mods_list) - 1 len_mods = len(self.mods_list) - 1
if lmods > 0: if len_mods > 0:
self.log.info(f"Loaded {lmods} mods: {round(self.mods_list[0] / MB, 2)}mb") # TODO: i18n
self.log.info(f"Loaded {len_mods} mods: {round(self.mods_list[0] / MB, 2)}mb")
self.log.info(i18n.init_ok)
await self.heartbeat(True) await self.heartbeat(True)
for i in range(int(config.Game["players"] * 1.3)): for i in range(int(config.Game["players"] * 2.3)): # * 2.3 For down sock and buffer.
self.clients.append(None) self.clients.append(None)
tasks = [] tasks = []
# self.udp.start, # self.udp.start,
nrtasks = [self.tcp.start, console.start, self.stop_me, self.heartbeat, self.check_alive] f_tasks = [self.tcp.start, console.start, self.stop_me, self.heartbeat, self.check_alive]
for task in nrtasks: for task in f_tasks:
tasks.append(asyncio.create_task(task())) tasks.append(asyncio.create_task(task()))
t = asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION) t = asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION)
await ev.call_async_event("_plugins_start")
self.run = True
self.log.info(i18n.start) self.log.info(i18n.start)
ev.call_event("on_started") ev.call_event("server_started")
await t await ev.call_async_event("server_started")
# Wait the end. await t # Wait end.
except KeyboardInterrupt:
pass
except Exception as e: except Exception as e:
self.log.error(f"Exception: {e}") self.log.error(f"Exception: {e}")
self.log.exception(e) self.log.exception(e)
except KeyboardInterrupt:
pass
finally: finally:
self.run = False
self.tcp.stop() self.tcp.stop()
# self.udp.stop() # self.udp.stop()
self.run = False await self.stop()
def start(self): def start(self):
asyncio.run(self.main()) asyncio.run(self.main())
def stop(self): async def stop(self):
ev.call_event("server_stopped")
await ev.call_async_event("server_stopped")
await ev.call_async_event("_plugins_unload")
self.run = False self.run = False
self.log.info(i18n.stop) self.log.info(i18n.stop)
if config.WebAPI["enabled"]: if config.WebAPI["enabled"]:
asyncio.run(self.web_stop()) asyncio.run(self.web_stop())
exit(0) # exit(0)

View File

@@ -1,46 +1,19 @@
# Developed by KuiToi Dev # Developed by KuiToi Dev
# File core.core.pyi # File core.core.pyi
# Written by: SantaSpeen # Written by: SantaSpeen
# Version 0.2.2 # Version 0.2.3
# Licence: FPA # Licence: FPA
# (c) kuitoi.su 2023 # (c) kuitoi.su 2023
import asyncio import asyncio
from asyncio import StreamWriter, StreamReader
from threading import Thread from threading import Thread
from typing import Callable, List, Dict, Tuple from typing import Callable, List, Dict
from core import utils from core import utils
from .Client import Client
from .tcp_server import TCPServer from .tcp_server import TCPServer
from .udp_server import UDPServer from .udp_server import UDPServer
class Client:
def __init__(self, reader: StreamReader, writer: StreamWriter, core: Core) -> "Client":
self.reader = reader
self.writer = writer
self.down_rw: Tuple[StreamReader, StreamWriter] | Tuple[None, None] = (None, None)
self.log = utils.get_logger("client(id: )")
self.addr = writer.get_extra_info("sockname")
self.loop = asyncio.get_event_loop()
self.Core = core
self.cid: int = -1
self.key: str = None
self.nick: str = None
self.roles: str = None
self.guest = True
self.alive = True
self.ready = False
def is_disconnected(self) -> bool: ...
async def kick(self, reason: str) -> None: ...
async def tcp_send(self, data: bytes, to_all:bool = False, writer: StreamWriter = None) -> None: ...
async def sync_resources(self) -> None: ...
async def recv(self) -> bytes: ...
async def _split_load(self, start: int, end: int, d_sock: bool, filename: str) -> None: ...
async def looper(self) -> None: ...
def _update_logger(self) -> None: ...
async def remove_me(self) -> None: ...
class Core: class Core:
def __init__(self): def __init__(self):
self.log = utils.get_logger("core") self.log = utils.get_logger("core")
@@ -72,4 +45,4 @@ class Core:
async def heartbeat(self, test=False) -> None: ... async def heartbeat(self, test=False) -> None: ...
async def main(self) -> None: ... async def main(self) -> None: ...
def start(self) -> None: ... def start(self) -> None: ...
def stop(self) -> None: ... async def stop(self) -> None: ...

View File

@@ -1,7 +1,7 @@
# Developed by KuiToi Dev # Developed by KuiToi Dev
# File core.tcp_server.py # File core.tcp_server.py
# Written by: SantaSpeen # Written by: SantaSpeen
# Core version: 0.2.2 # Core version: 0.2.3
# Licence: FPA # Licence: FPA
# (c) kuitoi.su 2023 # (c) kuitoi.su 2023
import asyncio import asyncio
@@ -23,37 +23,42 @@ class TCPServer:
async def auth_client(self, reader, writer): async def auth_client(self, reader, writer):
client = self.Core.create_client(reader, writer) client = self.Core.create_client(reader, writer)
# TODO: i18n
self.log.info(f"Identifying new ClientConnection...") self.log.info(f"Identifying new ClientConnection...")
data = await client.recv() data = await client._recv()
self.log.debug(f"Version: {data}") self.log.debug(f"Version: {data}")
if data.decode("utf-8") != f"VC{self.Core.client_major_version}": if data.decode("utf-8") != f"VC{self.Core.client_major_version}":
# TODO: i18n
await client.kick("Outdated Version.") await client.kick("Outdated Version.")
return False, client return False, client
else: else:
await client.tcp_send(b"S") # Accepted client version await client._send(b"S") # Accepted client version
data = await client.recv() data = await client._recv()
self.log.debug(f"Key: {data}") self.log.debug(f"Key: {data}")
if len(data) > 50: if len(data) > 50:
# TODO: i18n
await client.kick("Invalid Key (too long)!") await client.kick("Invalid Key (too long)!")
return False, client return False, client
client.key = data.decode("utf-8") client._key = data.decode("utf-8")
ev.call_event("auth_sent_key", client) ev.call_event("auth_sent_key", player=client)
try: try:
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
url = 'https://auth.beammp.com/pkToUser' url = 'https://auth.beammp.com/pkToUser'
async with session.post(url, data={'key': client.key}) as response: async with session.post(url, data={'key': client._key}) as response:
res = await response.json() res = await response.json()
self.log.debug(f"res: {res}") self.log.debug(f"res: {res}")
if res.get("error"): if res.get("error"):
# TODO: i18n
await client.kick('Invalid key! Please restart your game.') await client.kick('Invalid key! Please restart your game.')
return False, client return False, client
client.nick = res["username"] client._nick = res["username"]
client.roles = res["roles"] client._roles = res["roles"]
client.guest = res["guest"] client._guest = res["guest"]
# noinspection PyProtectedMember # noinspection PyProtectedMember
client._update_logger() client._update_logger()
except Exception as e: except Exception as e:
# TODO: i18n
self.log.error(f"Auth error: {e}") self.log.error(f"Auth error: {e}")
await client.kick('Invalid authentication data! Try to reconnect in 5 minutes.') await client.kick('Invalid authentication data! Try to reconnect in 5 minutes.')
return False, client return False, client
@@ -62,15 +67,18 @@ class TCPServer:
if not _client: if not _client:
continue continue
if _client.nick == client.nick and _client.guest == client.guest: if _client.nick == client.nick and _client.guest == client.guest:
# TODO: i18n
await client.kick('Stale Client (replaced by new client)') await client.kick('Stale Client (replaced by new client)')
return False, client return False, client
ev.call_event("auth_ok", client) ev.call_event("auth_ok", player=client)
if len(self.Core.clients_by_id) > config.Game["players"]: if len(self.Core.clients_by_id) > config.Game["players"]:
# TODO: i18n
await client.kick("Server full!") await client.kick("Server full!")
return False, client return False, client
else: else:
# TODO: i18n
self.log.info("Identification success") self.log.info("Identification success")
await self.Core.insert_client(client) await self.Core.insert_client(client)
@@ -81,7 +89,7 @@ class TCPServer:
cid = (await reader.read(1))[0] cid = (await reader.read(1))[0]
client = self.Core.get_client(cid=cid) client = self.Core.get_client(cid=cid)
if client: if client:
client.down_rw = (reader, writer) client._down_rw = (reader, writer)
self.log.debug(f"Client: {client.nick}:{cid} - HandleDownload!") self.log.debug(f"Client: {client.nick}:{cid} - HandleDownload!")
else: else:
writer.close() writer.close()
@@ -94,7 +102,7 @@ class TCPServer:
case "C": case "C":
result, client = await self.auth_client(reader, writer) result, client = await self.auth_client(reader, writer)
if result: if result:
await client.looper() await client._looper()
return result, client return result, client
case "D": case "D":
await self.set_down_rw(reader, writer) await self.set_down_rw(reader, writer)
@@ -103,6 +111,7 @@ class TCPServer:
await writer.drain() await writer.drain()
writer.close() writer.close()
case _: case _:
# TODO: i18n
self.log.error(f"Unknown code: {code}") self.log.error(f"Unknown code: {code}")
writer.close() writer.close()
return False, None return False, None
@@ -119,10 +128,11 @@ class TCPServer:
# await asyncio.wait([task], return_when=asyncio.FIRST_EXCEPTION) # await asyncio.wait([task], return_when=asyncio.FIRST_EXCEPTION)
_, cl = await self.handle_code(code, reader, writer) _, cl = await self.handle_code(code, reader, writer)
if cl: if cl:
await cl.remove_me() await cl._remove_me()
del cl del cl
break break
except Exception as e: except Exception as e:
# TODO: i18n
self.log.error("Error while connecting..") self.log.error("Error while connecting..")
self.log.exception(e) self.log.exception(e)
traceback.print_exc() traceback.print_exc()
@@ -139,9 +149,12 @@ class TCPServer:
async with server: async with server:
await server.serve_forever() await server.serve_forever()
except OSError as e: except OSError as e:
# TODO: i18n
self.log.error("Cannot bind port") self.log.error("Cannot bind port")
raise e raise e
except BaseException as e: except KeyboardInterrupt:
pass
except Exception as e:
self.log.error(f"Error: {e}") self.log.error(f"Error: {e}")
raise e raise e
finally: finally:

View File

@@ -1,7 +1,7 @@
# Developed by KuiToi Dev # Developed by KuiToi Dev
# File core.tcp_server.pyi # File core.tcp_server.pyi
# Written by: SantaSpeen # Written by: SantaSpeen
# Core version: 0.2.2 # Core version: 0.2.3
# Licence: FPA # Licence: FPA
# (c) kuitoi.su 2023 # (c) kuitoi.su 2023
import asyncio import asyncio
@@ -9,7 +9,7 @@ from asyncio import StreamWriter, StreamReader
from typing import Tuple from typing import Tuple
from core import utils, Core from core import utils, Core
from core.core import Client from core.Client import Client
class TCPServer: class TCPServer:

View File

@@ -1,7 +1,7 @@
# Developed by KuiToi Dev # Developed by KuiToi Dev
# File core.udp_server.py # File core.udp_server.py
# Written by: SantaSpeen # Written by: SantaSpeen
# Core version: 0.2.2 # Core version: 0.2.3
# Licence: FPA # Licence: FPA
# (c) kuitoi.su 2023 # (c) kuitoi.su 2023
import asyncio import asyncio

View File

@@ -1,7 +1,7 @@
# Developed by KuiToi Dev # Developed by KuiToi Dev
# File core.udp_server.py # File core.udp_server.py
# Written by: SantaSpeen # Written by: SantaSpeen
# Core version: 0.2.2 # Core version: 0.2.3
# Licence: FPA # Licence: FPA
# (c) kuitoi.su 2023 # (c) kuitoi.su 2023
import asyncio import asyncio

View File

@@ -2,7 +2,7 @@
# File core.utils.py # File core.utils.py
# Written by: SantaSpeen # Written by: SantaSpeen
# Version 1.1 # Version 1.1
# Core version: 0.2.2 # Core version: 0.2.3
# Licence: FPA # Licence: FPA
# (c) kuitoi.su 2023 # (c) kuitoi.su 2023
import datetime import datetime

View File

@@ -14,17 +14,13 @@ parser.add_argument('-v', '--version', action="store_true", help='Print version
parser.add_argument('--config', help='Patch to config file.', nargs='?', default=None, type=str) parser.add_argument('--config', help='Patch to config file.', nargs='?', default=None, type=str)
parser.add_argument('--language', help='Setting localisation.', nargs='?', default=None, type=str) parser.add_argument('--language', help='Setting localisation.', nargs='?', default=None, type=str)
run = True
def main(): def main():
from core import Core from core import Core
core = Core()
try: try:
core.start() Core().start()
except KeyboardInterrupt: except KeyboardInterrupt:
core.run = False pass
core.stop()
if __name__ == '__main__': if __name__ == '__main__':

View File

@@ -1,9 +1,9 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# Developed by KuiToi Dev # Developed by KuiToi Dev
# File core.config_provider.py # File modules.ConsoleSystem.console_system.py
# Written by: SantaSpeen # Written by: SantaSpeen
# Version 1.1 # Version 1.2
# Licence: FPA # Licence: FPA
# (c) kuitoi.su 2023 # (c) kuitoi.su 2023
import builtins import builtins
@@ -87,7 +87,7 @@ class Console:
print() print()
raw = True raw = True
message = str() message = "\n"
max_len = self.__get_max_len(self.__func.keys()) max_len = self.__get_max_len(self.__func.keys())
if max_len < 7: if max_len < 7:
max_len = 7 max_len = 7

View File

@@ -1,46 +1,99 @@
# -*- coding: utf-8 -*-
# Developed by KuiToi Dev
# File modules.EventsSystem.events_system.py
# Written by: SantaSpeen
# Version 1.0
# Licence: FPA
# (c) kuitoi.su 2023
import asyncio
import builtins import builtins
import inspect
from core import get_logger from core import get_logger
# noinspection PyShadowingBuiltins
class EventsSystem: class EventsSystem:
def __init__(self): def __init__(self):
self.__events = { # TODO: default events
"on_started": [self.on_started],
"on_stop": [self.on_stop],
"on_auth": [self.on_auth]
}
self.log = get_logger("EventsSystem") self.log = get_logger("EventsSystem")
self.loop = asyncio.get_event_loop()
self.as_tasks = []
self.__events = {
"server_started": [],
"auth_sent_key": [], # Only sync
"auth_ok": [], # Only sync
"player_join": [],
"chat_receive": [],
"server_stopped": [],
}
self.__async_events = {
"server_started": [],
"_plugins_start": [],
"_plugins_unload": [],
"player_join": [],
"chat_receive": [],
"server_stopped": []
}
def builtins_hook(self): def builtins_hook(self):
self.log.debug("used builtins_hook") self.log.debug("used builtins_hook")
builtins.ev = self builtins.ev = self
def register_event(self, event_name, event_func): def register_event(self, event_name, event_func, async_event=False):
self.log.debug(f"register_event({event_name}, {event_func}):") self.log.debug(f"register_event({event_name}, {event_func}):")
if not callable(event_func): if not callable(event_func):
# TODO: i18n
self.log.error(f"Cannot add event '{event_name}'. " self.log.error(f"Cannot add event '{event_name}'. "
f"Use `KuiToi.add_event({event_name}', function)` instead. Skipping it...") f"Use `KuiToi.add_event({event_name}', function)` instead. Skipping it...")
return return
if event_name not in self.__events: if async_event or inspect.iscoroutinefunction(event_func):
self.__events.update({str(event_name): [event_func]}) if event_name not in self.__async_events:
self.__async_events.update({str(event_name): [event_func]})
else:
self.__async_events[event_name].append(event_func)
else: else:
self.__events[event_name].append(event_func) if event_name not in self.__events:
self.__events.update({str(event_name): [event_func]})
else:
self.__events[event_name].append(event_func)
async def call_async_event(self, event_name, *args, **kwargs):
self.log.debug(f"Calling async event: '{event_name}'")
funcs_data = []
if event_name in self.__async_events.keys():
for func in self.__async_events[event_name]:
try:
event_data = {"event_name": event_name, "args": args, "kwargs": kwargs}
data = await func(event_data)
funcs_data.append(data)
except Exception as e:
# TODO: i18n
self.log.error(f'Error while calling "{event_name}"; In function: "{func.__name__}"')
self.log.exception(e)
else:
# TODO: i18n
self.log.warning(f"Event {event_name} does not exist, maybe ev.call_event()?. Just skipping it...")
return funcs_data
def call_event(self, event_name, *args, **kwargs):
self.log.debug(f"Calling sync event: '{event_name}'")
funcs_data = []
def call_event(self, event_name, *data):
self.log.debug(f"Using event '{event_name}'")
if event_name in self.__events.keys(): if event_name in self.__events.keys():
for event in self.__events[event_name]: for func in self.__events[event_name]:
event(*data) try:
event_data = {"event_name": event_name, "args": args, "kwargs": kwargs}
funcs_data.append(func(event_data))
except Exception as e:
# TODO: i18n
self.log.error(f'Error while calling "{event_name}"; In function: "{func.__name__}"')
self.log.exception(e)
else: else:
self.log.warning(f"Event {event_name} does not exist. Just skipping it...") # TODO: i18n
self.log.warning(f"Event {event_name} does not exist, maybe ev.call_async_event()?. Just skipping it...")
def on_started(self): return funcs_data
pass
def on_stop(self):
pass
def on_auth(self, client):
pass

View File

@@ -1,6 +1,11 @@
from typing import Any
class EventsSystem: class EventsSystem:
@staticmethod @staticmethod
def register_event(self, event_name, event_func): ... def register_event(event_name, event_func): ...
@staticmethod @staticmethod
def call_event(self, event_name, *data): ... async def call_async_event(event_name, *args, **kwargs) -> list[Any]: ...
@staticmethod
def call_event(event_name, *data, **kwargs) -> list[Any]: ...
class ev(EventsSystem): ... class ev(EventsSystem): ...

View File

@@ -1,52 +1,196 @@
# -*- coding: utf-8 -*-
# Developed by KuiToi Dev
# File modules.PluginsLoader.plugins_loader.py
# Written by: SantaSpeen
# Version 1.0
# Licence: FPA
# (c) kuitoi.su 2023
import asyncio
import inspect
import os import os
import types import types
from contextlib import contextmanager
from threading import Thread
from core import get_logger from core import get_logger
# TODO: call_client_event, get_player, get_players, GetPlayerCount
class KuiToi: class KuiToi:
_plugins_dir = ""
def __init__(self, name=None): def __init__(self, name=None):
if name is None: if name is None:
raise Exception("BeamMP: Name is required") raise AttributeError("KuiToi: Name is required")
self.log = get_logger(f"PluginsLoader | {name}") self.log = get_logger(f"Plugin | {name}")
self.name = name self.__name = name
self.__dir = os.path.join(self._plugins_dir, self.__name)
if not os.path.exists(self.__dir):
os.mkdir(self.__dir)
def set_name(self, name): @property
self.name = name def name(self):
return self.__name
@staticmethod @name.setter
def register_event(event_name, event_func): def name(self, value):
# You chell not pass
pass
@property
def dir(self):
return self.__dir
@dir.setter
def dir(self, value):
# You chell not pass
pass
@contextmanager
def open(self, file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None):
path = os.path.join(self.__dir, file)
self.log.debug(f'Trying to open "{path}" with mode "{mode}"')
# if not os.path.exists(path):
# with open(path, 'x'): ...
f = None
try:
f = open(path, mode, buffering, encoding, errors, newline, closefd, opener)
yield f
except Exception as e:
raise e
finally:
if f is not None:
f.close()
def register_event(self, event_name, event_func):
self.log.debug(f"Registering event {event_name}")
ev.register_event(event_name, event_func) ev.register_event(event_name, event_func)
@staticmethod def call_event(self, event_name, *data, **kwargs):
def call_event(event_name, *data): self.log.debug(f"Called event {event_name}")
ev.call_event(event_name, *data) ev.call_event(event_name, *data, **kwargs)
class PluginsLoader: class PluginsLoader:
def __init__(self, plugins_dir): def __init__(self, plugins_dir):
self.__plugins = {} self.loop = asyncio.get_event_loop()
self.__plugins_dir = plugins_dir self.plugins = {}
self.plugins_tasks = []
self.plugins_dir = plugins_dir
self.log = get_logger("PluginsLoader") self.log = get_logger("PluginsLoader")
self.loaded_str = "Plugins: "
ev.register_event("_plugins_start", self.start)
ev.register_event("_plugins_unload", self.unload)
console.add_command("plugins", lambda x: self.loaded_str[:-2])
console.add_command("pl", lambda x: self.loaded_str[:-2])
def load_plugins(self): async def load(self):
self.log.debug("Loading plugins...") self.log.debug("Loading plugins...")
files = os.listdir(self.__plugins_dir) files = os.listdir(self.plugins_dir)
for file in files: for file in files:
if file.endswith(".py"): if file.endswith(".py"):
try: try:
self.log.debug(f"Loading plugin: {file}") self.log.debug(f"Loading plugin: {file[:-3]}")
plugin = types.ModuleType('plugin') plugin = types.ModuleType(file[:-3])
plugin.KuiToi = KuiToi plugin.KuiToi = KuiToi
plugin.KuiToi._plugins_dir = self.plugins_dir
plugin.print = print plugin.print = print
file = os.path.join(self.__plugins_dir, file) file_path = os.path.join(self.plugins_dir, file)
with open(f'{file}', 'r') as f: plugin.__file__ = file_path
code = f.read().replace("import KuiToi\n", "") with open(f'{file_path}', 'r', encoding="utf-8") as f:
code = f.read()
exec(code, plugin.__dict__) exec(code, plugin.__dict__)
plugin.load()
self.__plugins.update({file[:-3]: plugin}) ok = True
self.log.debug(f"Plugin loaded: {file}") try:
isfunc = inspect.isfunction
if not isfunc(plugin.load):
self.log.error('Function "def load():" not found.')
ok = False
if not isfunc(plugin.start):
self.log.error('Function "def start():" not found.')
ok = False
if not isfunc(plugin.unload):
self.log.error('Function "def unload():" not found.')
ok = False
if type(plugin.kt) != KuiToi:
self.log.error(f'Attribute "kt" isn\'t KuiToi class. Plugin file: "{file_path}"')
ok = False
except AttributeError:
ok = False
if not ok:
self.log.error(f'Plugin file: "{file_path}" is not a valid KuiToi plugin.')
return
pl_name = plugin.kt.name
if self.plugins.get(pl_name) is not None:
raise NameError(f'Having plugins with identical names is not allowed; '
f'Plugin name: "{pl_name}"; Plugin file "{file_path}"')
plugin.open = plugin.kt.open
iscorfunc = inspect.iscoroutinefunction
self.plugins.update(
{
pl_name: {
"plugin": plugin,
"load": {
"func": plugin.load,
"async": iscorfunc(plugin.load)
},
"start": {
"func": plugin.start,
"async": iscorfunc(plugin.start)
},
"unload": {
"func": plugin.unload,
"async": iscorfunc(plugin.unload)
}
}
}
)
if self.plugins[pl_name]["load"]['async']:
plugin.log.debug(f"I'm async")
await plugin.load()
else:
plugin.log.debug(f"I'm sync")
th = Thread(target=plugin.load, name=f"{pl_name}.load()")
th.start()
th.join()
self.loaded_str += f"{pl_name}:ok, "
self.log.debug(f"Plugin loaded: {file}. Settings: {self.plugins[pl_name]}")
except Exception as e: except Exception as e:
self.log.error(f"Error loading plugin: {file}; Error: {e}") # TODO: i18n
self.loaded_str += f"{file}:no, "
self.log.error(f"Error while loading plugin: {file}; Error: {e}")
self.log.exception(e)
async def start(self, _):
for pl_name, pl_data in self.plugins.items():
try:
if pl_data['start']['async']:
self.log.debug(f"Start async plugin: {pl_name}")
t = self.loop.create_task(pl_data['start']['func']())
self.plugins_tasks.append(t)
else:
self.log.debug(f"Start sync plugin: {pl_name}")
th = Thread(target=pl_data['start']['func'], name=f"Thread {pl_name}")
th.start()
self.plugins_tasks.append(th)
except Exception as e:
self.log.exception(e)
async def unload(self, _):
for pl_name, pl_data in self.plugins.items():
try:
if pl_data['unload']['async']:
self.log.debug(f"Unload async plugin: {pl_name}")
await pl_data['unload']['func']()
else:
self.log.debug(f"Unload sync plugin: {pl_name}")
th = Thread(target=pl_data['unload']['func'], name=f"Thread {pl_name}")
th.start()
th.join()
except Exception as e:
self.log.exception(e)

View File

@@ -122,6 +122,5 @@ def hack_fastapi():
}) })
LOGGING_CONFIG["loggers"]["uvicorn"]["handlers"].append("file_default") LOGGING_CONFIG["loggers"]["uvicorn"]["handlers"].append("file_default")
LOGGING_CONFIG["loggers"]["uvicorn.access"]["handlers"].append("file_access") LOGGING_CONFIG["loggers"]["uvicorn.access"]["handlers"].append("file_access")
print(LOGGING_CONFIG)

View File

@@ -1,15 +1,15 @@
{ {
"": "Basic phases", "": "Basic phases",
"hello": "Hello from KuiToi-Server!", "hello": "Greetings from KuiToi Server!",
"config_path": "Use {} for config.", "config_path": "Use {} to configure.",
"init_ok": "Initializing ready.", "init_ok": "Initialization complete.",
"start": "Server started!", "start": "Server started!",
"stop": "Goodbye!", "stop": "Server stopped!",
"": "Server auth", "": "Server auth",
"auth_need_key": "BEAM key needed for starting the server!", "auth_need_key": "A BeamMP key is required to start the server!",
"auth_empty_key": "Key is empty!", "auth_empty_key": "The BeamMP key is empty!",
"auth_cannot_open_browser": "Cannot open browser: {}", "auth_cannot_open_browser": "Failed to open browser: {}",
"auth_use_link": "Use this link: {}", "auth_use_link": "Use this link: {}",
"": "GUI phases", "": "GUI phases",
@@ -17,32 +17,32 @@
"GUI_no": "No", "GUI_no": "No",
"GUI_ok": "Ok", "GUI_ok": "Ok",
"GUI_cancel": "Cancel", "GUI_cancel": "Cancel",
"GUI_need_key_message": "BEAM key needed for starting the server!\nDo you need to open the web link to obtain the key?", "GUI_need_key_message": "A BeamMP key is required to start the server!\nDo you want to open the link in a browser to obtain the key?",
"GUI_enter_key_message": "Please type your key:", "GUI_enter_key_message": "Please enter the key:",
"GUI_cannot_open_browser": "Cannot open browser.\nUse this link: {}", "GUI_cannot_open_browser": "Failed to open browser.\nUse this link: {}",
"": "Web phases", "": "Web phases",
"web_start": "WebAPI running on {} (Press CTRL+C to quit)", "web_start": "WebAPI started at {} (Press CTRL+C to quit)",
"": "Command: man", "": "Command: man",
"man_message_man": "man - display the manual page for COMMAND.\nUsage: man COMMAND", "man_message_man": "man - Displays help page for COMMAND.\nUsage: man COMMAND",
"help_message_man": "Display the manual page for COMMAND.", "help_message_man": "Displays help page for COMMAND.",
"man_for": "Manual for command", "man_for": "Help page for",
"man_message_not_found": "man: Manual message not found.", "man_message_not_found": "man: Help page not found.",
"man_command_not_found": "man: command \"{}\" not found!", "man_command_not_found": "man: Command \"{}\" not found!",
"": "Command: help", "": "Command: help",
"man_message_help": "help - display names and brief descriptions of available commands.\nUsage: help [--raw]\nThe `help` command displays a list of all available commands along with a brief description of each command.", "man_message_help": "help - Displays the names and short descriptions of commands.\nUsage: help [--raw]\nThe `help` command displays a list of all available commands and a brief description of each command.",
"help_message_help": "Display names and brief descriptions of available commands", "help_message_help": "Displays the names and short descriptions of commands.",
"help_command": "Command", "help_command": "Command",
"help_message": "Help message", "help_message": "Description",
"help_message_not_found": "No help message found", "help_message_not_found": "No description available.",
"": "Command: stop", "": "Command: stop",
"man_message_stop": "stop - Just shutting down the server.\nUsage: stop", "man_message_stop": "stop - Stops the server.\nUsage: stop",
"help_message_stop": "Server shutdown.", "help_message_stop": "Stops the server.",
"": "Command: exit", "": "Command: exit",
"man_message_exit": "exit - Just shutting down the server.\nUsage: stop", "man_message_exit": "exit - Stops the server.\nUsage: exit",
"help_message_exit": "Server shutdown." "help_message_exit": "Stops the server."
} }

View File

@@ -3,7 +3,7 @@
# Developed by KuiToi Dev # Developed by KuiToi Dev
# File modules.i18n.i18n.py # File modules.i18n.i18n.py
# Written by: SantaSpeen # Written by: SantaSpeen
# Version 1.0 # Version 1.3
# Licence: FPA # Licence: FPA
# (c) kuitoi.su 2023 # (c) kuitoi.su 2023
import builtins import builtins
@@ -89,53 +89,53 @@ class MultiLanguage:
else: else:
# noinspection PyDictDuplicateKeys # noinspection PyDictDuplicateKeys
self.__data = { self.__data = {
"": "Basic phases", "": "Basic phases",
"hello": "Hello from KuiToi-Server!", "hello": "Greetings from KuiToi Server!",
"config_path": "Use {} for config.", "config_path": "Use {} to configure.",
"init_ok": "Initializing ready.", "init_ok": "Initialization complete.",
"start": "Server started!", "start": "Server started!",
"stop": "Goodbye!", "stop": "Server stopped!",
"": "Server auth", "": "Server auth",
"auth_need_key": "BEAM key needed for starting the server!", "auth_need_key": "A BeamMP key is required to start the server!",
"auth_empty_key": "Key is empty!", "auth_empty_key": "The BeamMP key is empty!",
"auth_cannot_open_browser": "Cannot open browser: {}", "auth_cannot_open_browser": "Failed to open browser: {}",
"auth_use_link": "Use this link: {}", "auth_use_link": "Use this link: {}",
"": "GUI phases", "": "GUI phases",
"GUI_yes": "Yes", "GUI_yes": "Yes",
"GUI_no": "No", "GUI_no": "No",
"GUI_ok": "Ok", "GUI_ok": "Ok",
"GUI_cancel": "Cancel", "GUI_cancel": "Cancel",
"GUI_need_key_message": "BEAM key needed for starting the server!\nDo you need to open the web link to obtain the key?", "GUI_need_key_message": "A BeamMP key is required to start the server!\nDo you want to open the link in a browser to obtain the key?",
"GUI_enter_key_message": "Please type your key:", "GUI_enter_key_message": "Please enter the key:",
"GUI_cannot_open_browser": "Cannot open browser.\nUse this link: {}", "GUI_cannot_open_browser": "Failed to open browser.\nUse this link: {}",
"": "Web phases", "": "Web phases",
"web_start": "WebAPI running on {} (Press CTRL+C to quit)", "web_start": "WebAPI started at {} (Press CTRL+C to quit)",
"": "Command: man", "": "Command: man",
"man_message_man": "man - display the manual page for COMMAND.\nUsage: man COMMAND", "man_message_man": "man - Displays help page for COMMAND.\nUsage: man COMMAND",
"help_message_man": "Display the manual page for COMMAND.", "help_message_man": "Displays help page for COMMAND.",
"man_for": "Manual for command", "man_for": "Help page for",
"man_message_not_found": "man: Manual message not found.", "man_message_not_found": "man: Help page not found.",
"man_command_not_found": "man: command \"{}\" not found!", "man_command_not_found": "man: Command \"{}\" not found!",
"": "Command: help", "": "Command: help",
"man_message_help": "help - display names and brief descriptions of available commands.\nUsage: help [--raw]\nThe `help` command displays a list of all available commands along with a brief description of each command.", "man_message_help": "help - Displays the names and short descriptions of commands.\nUsage: help [--raw]\nThe `help` command displays a list of all available commands and a brief description of each command.",
"help_message_help": "Display names and brief descriptions of available commands", "help_message_help": "Displays the names and short descriptions of commands.",
"help_command": "Command", "help_command": "Command",
"help_message": "Help message", "help_message": "Description",
"help_message_not_found": "No help message found", "help_message_not_found": "No description available.",
"": "Command: stop", "": "Command: stop",
"man_message_stop": "stop - Just shutting down the server.\nUsage: stop", "man_message_stop": "stop - Stops the server.\nUsage: stop",
"help_message_stop": "Server shutdown.", "help_message_stop": "Stops the server.",
"": "Command: exit", "": "Command: exit",
"man_message_exit": "exit - Just shutting down the server.\nUsage: stop", "man_message_exit": "exit - Stops the server.\nUsage: exit",
"help_message_exit": "Server shutdown." "help_message_exit": "Stops the server."
} }
self.__i18n = i18n(self.__data) self.__i18n = i18n(self.__data)
def open_file(self): def open_file(self):