Moved config into scaffold, tweaks to init options

Changes for SRV resolution, get online_mode and legacy also from config
This commit is contained in:
əlemi 2022-05-23 01:11:06 +02:00
parent 3067032f1b
commit 5f2beac41b
No known key found for this signature in database
GPG key ID: BBCBFE5D7244634E
2 changed files with 24 additions and 25 deletions

View file

@ -1,3 +1,5 @@
from configparser import ConfigParser, SectionProxy
from typing import Type, Any from typing import Type, Any
from aiocraft.client import MinecraftClient from aiocraft.client import MinecraftClient
@ -22,29 +24,33 @@ class Scaffold(
Runnable, Runnable,
): ):
send_keep_alive : bool = True # TODO how to handle this? config: ConfigParser
@property
def cfg(self) -> SectionProxy:
return SectionProxy(self.config, "Treepuncher")
def on_packet(self, packet:Type[Packet]): def on_packet(self, packet:Type[Packet]):
def decorator(fun): def decorator(fun):
return self.register(packet, fun) return self.register(packet, fun)
return decorator return decorator
def on(self, event:Type[BaseEvent]): # TODO maybe move in Treepuncher? def on(self, event:Type[BaseEvent]):
def decorator(fun): def decorator(fun):
return self.register(event, fun) return self.register(event, fun)
return decorator return decorator
#Override #Override
async def _play(self) -> bool: async def _play(self) -> bool:
self.dispatcher.state = ConnectionState.PLAY self.dispatcher.set_state(ConnectionState.PLAY)
self.run_callbacks(ConnectedEvent, ConnectedEvent()) self.run_callbacks(ConnectedEvent, ConnectedEvent())
async for packet in self.dispatcher.packets(): async for packet in self.dispatcher.packets():
self.logger.debug("[ * ] Processing %s", packet.__class__.__name__) self.logger.debug("[ * ] Processing %s", packet.__class__.__name__)
if isinstance(packet, PacketSetCompression): if isinstance(packet, PacketSetCompression):
self.logger.info("Compression updated") self.logger.info("Compression updated")
self.dispatcher.compression = packet.threshold self.dispatcher.set_compression(packet.threshold)
elif isinstance(packet, PacketKeepAlive): elif isinstance(packet, PacketKeepAlive):
if self.send_keep_alive: if self.cfg.getboolean("send_keep_alive", fallback=True):
keep_alive_packet = PacketKeepAliveResponse(340, keepAliveId=packet.keepAliveId) keep_alive_packet = PacketKeepAliveResponse(340, keepAliveId=packet.keepAliveId)
await self.dispatcher.write(keep_alive_packet) await self.dispatcher.write(keep_alive_packet)
elif isinstance(packet, PacketKickDisconnect): elif isinstance(packet, PacketKickDisconnect):

View file

@ -4,10 +4,9 @@ import asyncio
import datetime import datetime
import pkg_resources import pkg_resources
from typing import Coroutine, List, Dict, Optional, Union, Any, Type, get_args, get_origin, get_type_hints, Set, Callable from typing import List, Dict, Any, Type
from time import time from time import time
from dataclasses import dataclass, MISSING, fields from configparser import ConfigParser
from configparser import ConfigParser, SectionProxy
from apscheduler.schedulers.asyncio import AsyncIOScheduler from apscheduler.schedulers.asyncio import AsyncIOScheduler
@ -16,13 +15,11 @@ from aiocraft.mc.auth import AuthInterface, AuthException, MojangAuthenticator,
from .storage import Storage, SystemState, AuthenticatorState from .storage import Storage, SystemState, AuthenticatorState
from .game import GameState, GameChat, GameInventory, GameTablist, GameWorld from .game import GameState, GameChat, GameInventory, GameTablist, GameWorld
from .scaffold import ConfigObject
from .addon import Addon from .addon import Addon
from .notifier import Notifier, Provider from .notifier import Notifier, Provider
__VERSION__ = pkg_resources.get_distribution('treepuncher').version __VERSION__ = pkg_resources.get_distribution('treepuncher').version
class MissingParameterError(Exception): class MissingParameterError(Exception):
pass pass
@ -34,7 +31,6 @@ class Treepuncher(
GameWorld GameWorld
): ):
name: str name: str
config: ConfigParser
storage: Storage storage: Storage
notifier: Notifier notifier: Notifier
@ -48,8 +44,6 @@ class Treepuncher(
self, self,
name: str, name: str,
config_file: str = None, config_file: str = None,
online_mode: bool = True,
legacy: bool = False,
**kwargs **kwargs
): ):
self.ctx = dict() self.ctx = dict()
@ -61,15 +55,17 @@ class Treepuncher(
authenticator : AuthInterface authenticator : AuthInterface
def opt(k:str, required=False, default=None) -> Any: def opt(k:str, required=False, default=None, t:type=str) -> Any:
v = kwargs.get(k) or self.cfg.get(k) or default v = kwargs.get(k) or self.cfg.get(k) or default
if not v and required: if not v and required:
raise MissingParameterError(f"Missing configuration parameter '{k}'") raise MissingParameterError(f"Missing configuration parameter '{k}'")
return v if t is bool and v.lower().strip() == 'false': # hardcoded special case
return False
return t(v)
if not online_mode: if not opt('online_mode', default=True, t=bool):
authenticator = OfflineAuthenticator(self.name) authenticator = OfflineAuthenticator(self.name)
elif legacy: elif opt('legacy', default=False, t=bool):
authenticator = MojangAuthenticator( authenticator = MojangAuthenticator(
username= opt('username', default=name, required=True), username= opt('username', default=name, required=True),
password= opt('password') password= opt('password')
@ -86,8 +82,10 @@ class Treepuncher(
super().__init__( super().__init__(
opt('server', required=True), opt('server', required=True),
online_mode=online_mode, authenticator=authenticator,
authenticator=authenticator online_mode=opt('online_mode', default=True, t=bool),
force_port=opt('force_port', default=0, t=int),
resolve_srv=opt('resolve_srv', default=False, t=bool),
) )
self.storage = Storage(self.name) self.storage = Storage(self.name)
@ -96,8 +94,7 @@ class Treepuncher(
self.modules = [] self.modules = []
# tz = datetime.datetime.now(datetime.timezone.utc).astimezone().tzname() # This doesn't work anymore self.scheduler = AsyncIOScheduler()
self.scheduler = AsyncIOScheduler() # TODO APScheduler warns about timezone ugghh
logging.getLogger('apscheduler.executors.default').setLevel(logging.WARNING) # So it's way less spammy logging.getLogger('apscheduler.executors.default').setLevel(logging.WARNING) # So it's way less spammy
self.scheduler.start(paused=True) self.scheduler.start(paused=True)
@ -117,10 +114,6 @@ class Treepuncher(
self.logger.info("Loaded session from %s", prev_auth.date) self.logger.info("Loaded session from %s", prev_auth.date)
self.storage._set_state(state) self.storage._set_state(state)
@property
def cfg(self) -> SectionProxy:
return SectionProxy(self.config, "Treepuncher")
@property @property
def playerName(self) -> str: def playerName(self) -> str:
return self.authenticator.selectedProfile.name return self.authenticator.selectedProfile.name