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.|
|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):

View file

@ -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())

View file

@ -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(

View file

@ -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:
@ -217,6 +217,18 @@ class AternosServer:
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:
return int(self._info['ram'])

View file

@ -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
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 ')
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

View file

@ -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',