Bugfixes in atconnect, atwss(async functions)

This commit is contained in:
DarkCat09 2022-05-18 18:33:21 +04:00
parent f606cfd521
commit b02e833702
6 changed files with 69 additions and 68 deletions

View file

@ -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.| |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.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.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.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 is planned.| |v1.3.x|Shared access API and Google Drive backups are planned.|
## License ## License
[License Notice](NOTICE): [License Notice](NOTICE):

View file

@ -24,16 +24,14 @@ async def main():
) )
async def commands(): async def commands():
try: while True:
while True: cmd = await aioconsole.ainput('> ')
cmd = await aioconsole.ainput('> ') if cmd.strip() == '':
await socket.send({ continue
'stream': 'console', await socket.send({
'type': 'command', 'stream': 'console',
'data': cmd 'type': 'command',
}) 'data': cmd
except KeyboardInterrupt: })
await socket.close()
print('* Exit')
asyncio.run(main()) asyncio.run(main())

View file

@ -3,24 +3,12 @@ import random
import logging import logging
from requests import Response from requests import Response
from cloudscraper import CloudScraper from cloudscraper import CloudScraper
from typing import Optional, Union, Dict from typing import Optional, Union
from . import atjsparse from . import atjsparse
from .aterrors import CredentialsError, CloudflareError 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' 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: class AternosConnect:
@ -109,12 +97,6 @@ class AternosConnect:
num //= base num //= base
return result 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( def request_cloudflare(
self, url:str, method:str, self, url:str, method:str,
params:Optional[dict]=None, data:Optional[dict]=None, params:Optional[dict]=None, data:Optional[dict]=None,
@ -129,13 +111,15 @@ class AternosConnect:
except KeyError: except KeyError:
pass pass
method = method or 'GET'
method = method.upper().strip()
if method not in ('GET', 'POST'): if method not in ('GET', 'POST'):
raise NotImplementedError('Only GET and POST are available') raise NotImplementedError('Only GET and POST are available')
headers = headers or {}
params = params or {} params = params or {}
data = data or {} data = data or {}
reqcookies = reqcookies or {} reqcookies = reqcookies or {}
headers = self.add_headers(headers)
if sendtoken: if sendtoken:
params['TOKEN'] = self.token params['TOKEN'] = self.token
@ -173,7 +157,7 @@ class AternosConnect:
params, data, params, data,
headers, reqcookies, headers, reqcookies,
sendtoken, redirect, sendtoken, redirect,
retry - 1 retry + 1
) )
logging.info( logging.info(

View file

@ -1,7 +1,7 @@
import enum import enum
import json import json
from requests import Response from requests import Response
from typing import Optional from typing import Optional, List
from .atconnect import AternosConnect from .atconnect import AternosConnect
from .aterrors import ServerError from .aterrors import ServerError
@ -186,7 +186,7 @@ class AternosServer:
@property @property
def address(self) -> str: def address(self) -> str:
return f'{self.domain}:{self.port}' return self._info['displayAddress']
@property @property
def domain(self) -> str: def domain(self) -> str:
@ -217,6 +217,18 @@ class AternosServer:
def status_num(self) -> int: def status_num(self) -> int:
return int(self._info['status']) 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 @property
def ram(self) -> int: def ram(self) -> int:
return int(self._info['ram']) return int(self._info['ram'])

View file

@ -88,6 +88,8 @@ class AternosWss:
async def close(self) -> None: async def close(self) -> None:
self.keep.cancel()
self.msgs.cancel()
await self.socket.close() await self.socket.close()
del self.socket del self.socket
@ -100,42 +102,48 @@ class AternosWss:
async def wssworker(self) -> None: async def wssworker(self) -> None:
keep = asyncio.create_task(self.keepalive()) self.keep = asyncio.create_task(self.keepalive())
msgs = asyncio.create_task(self.receiver()) self.msgs = asyncio.create_task(self.receiver())
await keep
await msgs
async def keepalive(self) -> None: async def keepalive(self) -> None:
while True: try:
await asyncio.sleep(49) while True:
await self.socket.send('{"type":"\u2764"}') await asyncio.sleep(49)
await self.socket.send('{"type":"\u2764"}')
except asyncio.CancelledError:
pass
async def receiver(self) -> None: async def receiver(self) -> None:
while True: try:
data = await self.socket.recv() while True:
obj = json.loads(data) data = await self.socket.recv()
msgtype = -1 obj = json.loads(data)
msgtype = -1
if obj['type'] == 'line': if obj['type'] == 'line':
msgtype = Streams.console msgtype = Streams.console
msg = obj['data'].strip('\r\n ') msg = obj['data'].strip('\r\n ')
elif obj['type'] == 'heap': elif obj['type'] == 'heap':
msgtype = Streams.ram msgtype = Streams.ram
msg = int(obj['data']['usage']) msg = int(obj['data']['usage'])
elif obj['type'] == 'tick': elif obj['type'] == 'tick':
msgtype = Streams.tps msgtype = Streams.tps
ticks = 1000 / obj['data']['averageTickTime'] ticks = 1000 / obj['data']['averageTickTime']
msg = 20 if ticks > 20 else ticks msg = 20 if ticks > 20 else ticks
elif obj['type'] == 'status': elif obj['type'] == 'status':
msgtype = Streams.status msgtype = Streams.status
msg = json.loads(obj['message']) msg = json.loads(obj['message'])
if msgtype in self.recv: if msgtype in self.recv:
asyncio.create_task( await asyncio.create_task(
self.recv[msgtype](msg) self.recv[msgtype](msg)
) )
except asyncio.CancelledError:
pass

View file

@ -5,7 +5,7 @@ with open('README.md', 'rt') as readme:
setuptools.setup( setuptools.setup(
name='python-aternos', name='python-aternos',
version='1.0.3', version='1.0.4',
author='Chechkenev Andrey (@DarkCat09)', author='Chechkenev Andrey (@DarkCat09)',
author_email='aacd0709@mail.ru', author_email='aacd0709@mail.ru',
description='An unofficial Aternos API', description='An unofficial Aternos API',
@ -29,8 +29,7 @@ setuptools.setup(
'Operating System :: OS Independent', 'Operating System :: OS Independent',
'Operating System :: Microsoft :: Windows', 'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX :: Linux', 'Operating System :: POSIX :: Linux',
'Operating System :: MacOS', 'Operating System :: MacOS'
'Operating System :: Other OS'
], ],
install_requires=[ install_requires=[
'lxml>=4.8.0', 'lxml>=4.8.0',