From b02e8337025cc4fec4f3caf0fc2e0060cbc39cb2 Mon Sep 17 00:00:00 2001 From: DarkCat09 Date: Wed, 18 May 2022 18:33:21 +0400 Subject: [PATCH] Bugfixes in atconnect, atwss(async functions) --- README.md | 4 +-- examples/console_example.py | 20 +++++------ python_aternos/atconnect.py | 26 +++------------ python_aternos/atserver.py | 16 +++++++-- python_aternos/atwss.py | 66 +++++++++++++++++++++---------------- setup.py | 5 ++- 6 files changed, 69 insertions(+), 68 deletions(-) diff --git a/README.md b/README.md index 8fa160c..a876fc0 100644 --- a/README.md +++ b/README.md @@ -73,8 +73,8 @@ The documentation have not made yet. View examples and ask in the issues. |v0.6/v1.0.0|Code refactoring, websockets API and session saving to prevent detecting automation access.| |v1.0.x|Lots of bugfixes, changed versioning (SemVer).| |v1.1.x|Switching to selenium with [a custom Chrome driver](https://github.com/ultrafunkamsterdam/undetected-chromedriver), writing API documentation.| -|v1.2.x|Full implementation of config and software API, unit tests and documentation is planned.| -|v1.3.x|Shared access API and Google Drive backups is planned.| +|v1.2.x|Full implementation of config and software API, unit tests and documentation are planned.| +|v1.3.x|Shared access API and Google Drive backups are planned.| ## License [License Notice](NOTICE): diff --git a/examples/console_example.py b/examples/console_example.py index a63a90c..73f0715 100644 --- a/examples/console_example.py +++ b/examples/console_example.py @@ -24,16 +24,14 @@ async def main(): ) async def commands(): - try: - while True: - cmd = await aioconsole.ainput('> ') - await socket.send({ - 'stream': 'console', - 'type': 'command', - 'data': cmd - }) - except KeyboardInterrupt: - await socket.close() - print('* Exit') + while True: + cmd = await aioconsole.ainput('> ') + if cmd.strip() == '': + continue + await socket.send({ + 'stream': 'console', + 'type': 'command', + 'data': cmd + }) asyncio.run(main()) diff --git a/python_aternos/atconnect.py b/python_aternos/atconnect.py index bdc8b3b..44d539c 100644 --- a/python_aternos/atconnect.py +++ b/python_aternos/atconnect.py @@ -3,24 +3,12 @@ import random import logging from requests import Response from cloudscraper import CloudScraper -from typing import Optional, Union, Dict +from typing import Optional, Union from . import atjsparse from .aterrors import CredentialsError, CloudflareError REQUA = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36 OPR/85.0.4341.47' -REQHEADERS = { - 'Host': 'aternos.org', - 'User-Agent': REQUA, - 'Sec-Ch-Ua': '" Not A;Brand";v="99", "Chromium";v="100", "Opera";v="86"', - 'Sec-Ch-Ua-Mobile': '?0', - 'Sec-Ch-Ua-Platform': '"Linux"', - 'Sec-Fetch-Dest': 'document', - 'Sec-Fetch-Mode': 'navigate', - 'Sec-Fetch-Site': 'same-origin', - 'Sec-Fetch-User': '?1', - 'Upgrade-Insecure-Requests': '1' -} class AternosConnect: @@ -109,12 +97,6 @@ class AternosConnect: num //= base return result - def add_headers(self, headers:Optional[Dict[str,str]]=None) -> Dict[str,str]: - - headers = headers or {} - headers.update(REQHEADERS) - return headers - def request_cloudflare( self, url:str, method:str, params:Optional[dict]=None, data:Optional[dict]=None, @@ -129,13 +111,15 @@ class AternosConnect: except KeyError: pass + method = method or 'GET' + method = method.upper().strip() if method not in ('GET', 'POST'): raise NotImplementedError('Only GET and POST are available') + headers = headers or {} params = params or {} data = data or {} reqcookies = reqcookies or {} - headers = self.add_headers(headers) if sendtoken: params['TOKEN'] = self.token @@ -173,7 +157,7 @@ class AternosConnect: params, data, headers, reqcookies, sendtoken, redirect, - retry - 1 + retry + 1 ) logging.info( diff --git a/python_aternos/atserver.py b/python_aternos/atserver.py index ba99dc9..358ba7b 100644 --- a/python_aternos/atserver.py +++ b/python_aternos/atserver.py @@ -1,7 +1,7 @@ import enum import json from requests import Response -from typing import Optional +from typing import Optional, List from .atconnect import AternosConnect from .aterrors import ServerError @@ -186,7 +186,7 @@ class AternosServer: @property def address(self) -> str: - return f'{self.domain}:{self.port}' + return self._info['displayAddress'] @property def domain(self) -> str: @@ -216,6 +216,18 @@ class AternosServer: @property def status_num(self) -> int: return int(self._info['status']) + + @property + def players_list(self) -> List[str]: + return self._info['playerlist'] + + @property + def players_count(self) -> int: + return int(self._info['players']) + + @property + def slots(self) -> int: + return int(self._info['slots']) @property def ram(self) -> int: diff --git a/python_aternos/atwss.py b/python_aternos/atwss.py index 5facfd0..5c8636b 100644 --- a/python_aternos/atwss.py +++ b/python_aternos/atwss.py @@ -88,6 +88,8 @@ class AternosWss: async def close(self) -> None: + self.keep.cancel() + self.msgs.cancel() await self.socket.close() del self.socket @@ -100,42 +102,48 @@ class AternosWss: async def wssworker(self) -> None: - keep = asyncio.create_task(self.keepalive()) - msgs = asyncio.create_task(self.receiver()) - await keep - await msgs + self.keep = asyncio.create_task(self.keepalive()) + self.msgs = asyncio.create_task(self.receiver()) async def keepalive(self) -> None: - while True: - await asyncio.sleep(49) - await self.socket.send('{"type":"\u2764"}') + try: + while True: + await asyncio.sleep(49) + await self.socket.send('{"type":"\u2764"}') + + except asyncio.CancelledError: + pass async def receiver(self) -> None: - while True: - data = await self.socket.recv() - obj = json.loads(data) - msgtype = -1 - - if obj['type'] == 'line': - msgtype = Streams.console - msg = obj['data'].strip('\r\n ') + try: + while True: + data = await self.socket.recv() + obj = json.loads(data) + msgtype = -1 + + if obj['type'] == 'line': + msgtype = Streams.console + msg = obj['data'].strip('\r\n ') - elif obj['type'] == 'heap': - msgtype = Streams.ram - msg = int(obj['data']['usage']) + elif obj['type'] == 'heap': + msgtype = Streams.ram + msg = int(obj['data']['usage']) - elif obj['type'] == 'tick': - msgtype = Streams.tps - ticks = 1000 / obj['data']['averageTickTime'] - msg = 20 if ticks > 20 else ticks + elif obj['type'] == 'tick': + msgtype = Streams.tps + ticks = 1000 / obj['data']['averageTickTime'] + msg = 20 if ticks > 20 else ticks - elif obj['type'] == 'status': - msgtype = Streams.status - msg = json.loads(obj['message']) + elif obj['type'] == 'status': + msgtype = Streams.status + msg = json.loads(obj['message']) - if msgtype in self.recv: - asyncio.create_task( - self.recv[msgtype](msg) - ) + if msgtype in self.recv: + await asyncio.create_task( + self.recv[msgtype](msg) + ) + + except asyncio.CancelledError: + pass diff --git a/setup.py b/setup.py index 0c58962..4106bc9 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ with open('README.md', 'rt') as readme: setuptools.setup( name='python-aternos', - version='1.0.3', + version='1.0.4', author='Chechkenev Andrey (@DarkCat09)', author_email='aacd0709@mail.ru', description='An unofficial Aternos API', @@ -29,8 +29,7 @@ setuptools.setup( 'Operating System :: OS Independent', 'Operating System :: Microsoft :: Windows', 'Operating System :: POSIX :: Linux', - 'Operating System :: MacOS', - 'Operating System :: Other OS' + 'Operating System :: MacOS' ], install_requires=[ 'lxml>=4.8.0',