astandy 0.2.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Astandy/__init__.py ADDED
@@ -0,0 +1,42 @@
1
+ from .client import StandClient
2
+ from .updates import *
3
+
4
+ import logging
5
+ import os
6
+ import datetime
7
+
8
+ LOG_DIR = "astandy_logs"
9
+ if not os.path.exists(LOG_DIR):
10
+ os.mkdir(LOG_DIR)
11
+
12
+ for file in os.listdir(LOG_DIR):
13
+ if file.endswith(".log"):
14
+ try:
15
+ os.rename(f"{LOG_DIR}/{file}", f"{LOG_DIR}/{file}.old")
16
+ except FileNotFoundError:
17
+ pass
18
+
19
+ old_logs = sorted(
20
+ [f for f in os.listdir(LOG_DIR) if f.endswith(".log.old")],
21
+ key=lambda x: os.path.getmtime(f'{LOG_DIR}/{x}'),
22
+ reverse=True
23
+ )
24
+
25
+ for file in old_logs[5:]:
26
+ try:
27
+ os.remove(f'{LOG_DIR}/{file}')
28
+ except FileNotFoundError:
29
+ pass
30
+
31
+ logging.basicConfig(
32
+ level=logging.INFO,
33
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
34
+ handlers=[
35
+ logging.StreamHandler(),
36
+ logging.FileHandler(f"astandy_logs/client-{datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.log")
37
+ ]
38
+ )
39
+
40
+ __all__ = [
41
+ "StandClient"
42
+ ]
Astandy/cipher.py ADDED
@@ -0,0 +1,58 @@
1
+ from cryptography.hazmat.backends import default_backend
2
+ from cryptography.hazmat.primitives import padding
3
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
4
+
5
+ class AstandyCipher:
6
+ START_KEY = b"key_abcdefghijkl"
7
+ START_IV = b"iv_abcdefghijklm"
8
+
9
+ def __init__(self):
10
+ self._aes_cipher = Cipher(
11
+ algorithms.AES(AstandyCipher.START_KEY),
12
+ modes.CBC(AstandyCipher.START_IV),
13
+ backend=default_backend()
14
+ )
15
+
16
+ def new_aes_cipher(self, key, iv):
17
+ """
18
+ Create a new AES cipher for client
19
+
20
+ :param key: AES key
21
+ :param iv: Initialization vector
22
+ """
23
+ self._aes_cipher = Cipher(
24
+ algorithms.AES(key),
25
+ modes.CBC(iv),
26
+ backend=default_backend()
27
+ )
28
+
29
+
30
+ def encrypt(self, data: bytes):
31
+ """
32
+ Encrypt data with client's AES cipher
33
+
34
+ :param data: Data to encrypt
35
+ :return: Encrypted data
36
+ """
37
+ encryptor = self._aes_cipher.encryptor()
38
+
39
+ padder = padding.PKCS7(algorithms.AES.block_size).padder()
40
+ padded = padder.update(data) + padder.finalize()
41
+ encrypted = encryptor.update(padded) + encryptor.finalize()
42
+
43
+ return encrypted
44
+
45
+ def decrypt(self, data: bytes):
46
+ """
47
+ Decrypt data with client's AES cipher
48
+
49
+ :param data: Data to decrypt
50
+ :return: Decrypted data
51
+ """
52
+ decryptor = self._aes_cipher.decryptor()
53
+ decrypted_data = decryptor.update(data) + decryptor.finalize()
54
+
55
+ unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
56
+ decrypted = unpadder.update(decrypted_data) + unpadder.finalize()
57
+
58
+ return decrypted
Astandy/client.py ADDED
@@ -0,0 +1,355 @@
1
+ import asyncio
2
+ import socket
3
+ import ssl
4
+ from threading import Thread, Event
5
+ from time import sleep
6
+ from uuid import uuid4
7
+
8
+ import lz4.block
9
+ from python_socks.async_.asyncio import Proxy
10
+ from python_socks._types import ProxyType
11
+
12
+ from .dispatcher import Dispatcher
13
+ from .cipher import AstandyCipher
14
+ from .events import BaseEvents
15
+ from .types.extras import ConnectionInfo
16
+ from .generated import Generated, CADATA, GeneratedEvent, GENERATED_UPDATES, UPDATE_INDEX
17
+ from .services import Services
18
+ from .logging import AstandyLoggers
19
+ from .updates import Connected
20
+ from .utils import run_on_uvloop
21
+ from .parser import Parser
22
+ from .schemes.messages_pb2 import Response, ServerMsg
23
+ from .errors import AstandyRPCException
24
+
25
+ REQUEST_TIMEOUT = 15
26
+
27
+
28
+ class StandClient(Services, BaseEvents, Generated):
29
+ """
30
+ Client, the main means for interacting with game server.
31
+
32
+ :param handshake: Handshake to authorize client
33
+ :param ping_timeout: [Default: 15] Maximum time (in seconds) to wait for a ping response.
34
+ :param alias_name: [Default: class name] The name of the client used in custom logging.
35
+ :param reconnect_enable: [Default: True] If it is True client will try to reconnect after connection closed
36
+ """
37
+ SERVER_HOST = "server.boltgaming.io"
38
+ SERVER_PORT = 2223
39
+
40
+ def __init__(self,
41
+ handshake: str,
42
+ ping_timeout=15,
43
+ alias_name = '',
44
+ reconnect_enable=True,
45
+ host=None,
46
+ port=None,
47
+ username=None,
48
+ password=None,
49
+ max_retry_count=3
50
+ ):
51
+ super().__init__()
52
+ Services.__init__(self)
53
+
54
+ self.ping_timeout = ping_timeout
55
+ self.reconnect_enable = reconnect_enable
56
+ self.proxy_host = host
57
+ self.proxy_port = port
58
+ self.proxy_username = username
59
+ self.proxy_password = password
60
+ self.max_retry_count = max_retry_count
61
+
62
+ self._handshake = handshake
63
+ if not alias_name: alias_name = self.__class__.__name__
64
+
65
+ self._dp = Dispatcher(self)
66
+ self._reader: asyncio.StreamReader = None
67
+ self._writer: asyncio.StreamWriter = None
68
+ self._sock: socket.socket = None
69
+ self._loop = None
70
+
71
+ self._running = False
72
+ self._stopped = False
73
+ self._is_first_connect = True
74
+ self._connect_attempts_number = 0
75
+ self._connect_info: ConnectionInfo = ConnectionInfo()
76
+ self._pending_ping: asyncio.Event = asyncio.Event()
77
+ self._reconnecting: asyncio.Event = asyncio.Event()
78
+ self._pending_requests: dict[str, asyncio.Future] = {}
79
+
80
+ self._connected = asyncio.Event()
81
+ self._disconnected = asyncio.Event()
82
+ self._send_lock = asyncio.Lock()
83
+ self._authenticated = asyncio.Event()
84
+
85
+ self.cipher: AstandyCipher
86
+ self._logger = AstandyLoggers.get_logger(alias_name)
87
+
88
+ @property
89
+ def logger(self):
90
+ return self._logger
91
+
92
+ async def _connect_proxy(self):
93
+ proxy = Proxy(
94
+ proxy_type=ProxyType.SOCKS5,
95
+ host=self.proxy_host,
96
+ port=self.proxy_port,
97
+ username=self.proxy_username,
98
+ password=self.proxy_password
99
+ )
100
+
101
+ return await proxy.connect(
102
+ dest_host=StandClient.SERVER_HOST,
103
+ dest_port=StandClient.SERVER_PORT
104
+ )
105
+
106
+ async def _connect(self):
107
+ await self._disconnect()
108
+
109
+ context = ssl.create_default_context()
110
+ if not CADATA:
111
+ context.check_hostname = False
112
+ context.verify_mode = ssl.CERT_NONE
113
+ else:
114
+ context.load_verify_locations(cadata=CADATA)
115
+
116
+ host = StandClient.SERVER_HOST
117
+ port = StandClient.SERVER_PORT
118
+ sock = None
119
+ if self.proxy_host and self.proxy_port:
120
+ host = None
121
+ port = None
122
+ self._sock = await self._connect_proxy()
123
+
124
+ self._reader, self._writer = await asyncio.open_connection(
125
+ host=host,
126
+ port=port,
127
+ sock=self._sock,
128
+ ssl=context,
129
+ server_hostname=StandClient.SERVER_HOST
130
+ )
131
+
132
+ self._running = True
133
+
134
+ async def _disconnect(self):
135
+ try:
136
+ if self._writer:
137
+ self._writer.close()
138
+ await self._writer.wait_closed()
139
+
140
+ if self._sock:
141
+ self._sock.close()
142
+ except ssl.SSLError:
143
+ self.logger.warning('Server sent data after connection closed!')
144
+
145
+ self._disconnected.set()
146
+ self._authenticated.clear()
147
+ self._connected.clear()
148
+
149
+ async def start(self):
150
+ """
151
+ Start the client.
152
+
153
+ This method connects the client to game.
154
+ :raises ConnectionError: If the connection to game servers fails
155
+ """
156
+ self._run_task = asyncio.create_task(self._run())
157
+ wait_task = asyncio.create_task(self._authenticated.wait())
158
+
159
+ done, pending = await asyncio.wait(
160
+ [self._run_task, wait_task],
161
+ return_when=asyncio.FIRST_COMPLETED
162
+ )
163
+
164
+ if self._run_task in done:
165
+ self._authenticated.set()
166
+ await wait_task
167
+ if self._run_task.exception(): raise self._run_task.exception()
168
+
169
+ async def idle(self):
170
+ """
171
+ Block thread while client running.
172
+
173
+ """
174
+ while self._running:
175
+ await asyncio.sleep(0.1)
176
+
177
+
178
+ async def _run(self):
179
+ self._loop = asyncio.get_event_loop()
180
+
181
+ while not self._stopped and (self.reconnect_enable or self._is_first_connect):
182
+ self._connect_attempts_number += 1
183
+
184
+ if self._connect_attempts_number > self.max_retry_count: raise ConnectionError
185
+
186
+ if not self._is_first_connect: self.logger.info('Reconnecting!')
187
+ self.cipher = AstandyCipher()
188
+ self.generate_keys()
189
+
190
+ try:
191
+ await self._connect()
192
+ self._connected.set()
193
+
194
+ asyncio.create_task(self._initialize())
195
+ except Exception as e:
196
+ self.logger.warning(f'Connection failed {e}!')
197
+
198
+
199
+ await self._read_loop()
200
+
201
+ await self._disconnect()
202
+
203
+ async def _initialize(self):
204
+ try:
205
+ await self.hello()
206
+ await self.handshake(self._handshake)
207
+ asyncio.create_task(self._ping_loop())
208
+ self._authenticated.set()
209
+
210
+ if not self._is_first_connect: self.logger.info('Reconnected!')
211
+ self._is_first_connect = False
212
+ self._connect_attempts_number = 0
213
+
214
+ await self._dp.call_listeners(Connected())
215
+ except AstandyRPCException as ex:
216
+ self.logger.critical(f'Failed to authorize {ex}!')
217
+ self._running = False
218
+
219
+
220
+ async def _read_loop(self):
221
+ while self._running:
222
+ await asyncio.sleep(0.001)
223
+ msg_leng = await self._read_header()
224
+ if msg_leng <= 0: continue
225
+
226
+ msg = await self._read_exactly(msg_leng, timeout=1)
227
+ if not msg: continue
228
+
229
+ if msg == b'\x01':
230
+ self._pending_ping.set()
231
+ continue
232
+
233
+ asyncio.create_task(self._handle_msg(Parser.parse_response(msg)))
234
+ self._running = False
235
+
236
+ async def _ping_loop(self):
237
+ self._logger.extra = self._connect_info
238
+ while self._running:
239
+ self._pending_ping.clear()
240
+ start_time = asyncio.get_event_loop().time()
241
+
242
+ if not await self.send_payload(b'\x01'):
243
+ self._logger.critical('Failed to send ping!')
244
+ try:
245
+ await asyncio.wait_for(self._pending_ping.wait(), timeout=self.ping_timeout)
246
+ except asyncio.TimeoutError:
247
+ self._running = False
248
+ self._logger.critical('Ping not received!')
249
+ break
250
+
251
+ self._connect_info.ping = int((asyncio.get_event_loop().time() - start_time) * 1000)
252
+
253
+ await asyncio.sleep(5)
254
+
255
+
256
+ async def _read_exactly(self, size: int, timeout: float = 0.1) -> bytes | None:
257
+ try:
258
+ return await asyncio.wait_for(self._reader.readexactly(size), timeout=timeout)
259
+ except asyncio.TimeoutError:
260
+ return None
261
+ except asyncio.IncompleteReadError:
262
+ self._running = False
263
+ self._logger.critical("Connection closed by server!")
264
+ return None
265
+ except Exception as e:
266
+ self._logger.exception(f"Unexpected error while sending payload: {e}")
267
+ return None
268
+
269
+ async def _read_header(self):
270
+ header = await self._read_exactly(4)
271
+ if not header: return -1
272
+ return int.from_bytes(header, byteorder='big')
273
+
274
+ async def _handle_msg(self, server_msg: ServerMsg):
275
+ for response in server_msg.responses:
276
+ if response.id in self._pending_requests:
277
+ self._pending_requests[response.id].set_result(response)
278
+ else:
279
+ self._logger.warning(f"Skipped {response.id} response!")
280
+
281
+ for event in server_msg.events:
282
+ if GeneratedEvent.has_value(event.code):
283
+ await self._dp.call_listeners(GENERATED_UPDATES[event.code][UPDATE_INDEX[event.code]](event.params.one))
284
+ else:
285
+ self.logger.warning(f"Unknown event code {event.code}!")
286
+
287
+ for compressed in server_msg.compressed_instances:
288
+ data = lz4.block.decompress(compressed.compressed, uncompressed_size=compressed.uncompressed_size)
289
+ await self._handle_msg(Parser.parse_response(data))
290
+
291
+ async def send_request(self, code:int, request: bytes) -> Response:
292
+ """
293
+ Sending request to game servers
294
+
295
+ :param code: RPC method code
296
+ :param request: RPC payload
297
+ """
298
+ uuid = str(uuid4())
299
+ future = asyncio.get_event_loop().create_future()
300
+ self._pending_requests[uuid] = future
301
+
302
+ result: Response = Response()
303
+ if not await self._send_payload(Parser.new_msg(uuid, code, request)):
304
+ self._pending_requests.pop(uuid)
305
+ raise ConnectionError("Failed to send payload: Connection lost or closed.")
306
+
307
+ try:
308
+ result = await asyncio.wait_for(future, timeout=REQUEST_TIMEOUT)
309
+ except asyncio.TimeoutError:
310
+ self._logger.warning(f"Request {uuid} timeout after {REQUEST_TIMEOUT} seconds")
311
+ finally:
312
+ self._pending_requests.pop(uuid)
313
+
314
+ return result
315
+
316
+ async def _send_payload(self, payload):
317
+ await self._connected.wait()
318
+ if not self._running or not self._writer: return False
319
+
320
+ async with self._send_lock:
321
+ try:
322
+ self._writer.write(len(payload).to_bytes(4, byteorder='big')+payload)
323
+ await self._writer.drain()
324
+ return True
325
+ except (BrokenPipeError, ConnectionResetError):
326
+ self._logger.critical("Connection lost while sending data.")
327
+ return False
328
+ except Exception as e:
329
+ self._logger.exception(f"Unexpected error while sending payload: {e}")
330
+ return False
331
+
332
+ async def send_payload(self, payload: bytes):
333
+ """
334
+ Sends a payload to the server.
335
+
336
+ :param payload: The data to be sent.
337
+ :return: True if the payload was successfully sent else False.
338
+ """
339
+ if not await self._send_payload(payload):
340
+ self._running = False
341
+ return False
342
+ return True
343
+
344
+ async def stop(self):
345
+ """
346
+ Stop the client.
347
+ """
348
+ if not self._running: return
349
+ self._disconnected.clear()
350
+ self._stopped = True
351
+ self._running = False
352
+ await self._disconnected.wait()
353
+
354
+
355
+
Astandy/dispatcher.py ADDED
@@ -0,0 +1,19 @@
1
+ import asyncio
2
+ from collections import defaultdict
3
+
4
+ from .types.update import Update
5
+ from .listener import Listener
6
+ from .enums.events import BaseEvent
7
+
8
+ class Dispatcher():
9
+ def __init__(self, client):
10
+ super().__init__()
11
+ self._client = client
12
+ self.listeners: dict[int, Listener] = defaultdict(list[Listener])
13
+
14
+ def add_listener(self, listener: Listener):
15
+ self.listeners[listener.event].append(listener)
16
+
17
+ async def call_listeners(self, update: Update):
18
+ for listener in self.listeners[update.event]:
19
+ asyncio.create_task(listener.call(self._client, update))
File without changes
@@ -0,0 +1,9 @@
1
+ from enum import Enum
2
+
3
+ class Event(Enum):
4
+ pass
5
+
6
+ class BaseEvent(Event):
7
+ UNKNOWN = -1
8
+ CONNECT = 0
9
+ AUTHENTICATED = 1
Astandy/errors.py ADDED
@@ -0,0 +1 @@
1
+ class AstandyRPCException(Exception): pass
@@ -0,0 +1,10 @@
1
+ from .onConnect import OnConnect
2
+
3
+ class BaseEvents(
4
+ OnConnect
5
+ ): pass
6
+
7
+
8
+ __all__ = [
9
+ "BaseEvents"
10
+ ]
@@ -0,0 +1,16 @@
1
+ from collections.abc import Callable
2
+
3
+ from Astandy import listeners
4
+
5
+ class OnConnect:
6
+
7
+ def OnConnect(self) -> Callable:
8
+ """
9
+ **Decorator!** Register callback on connect event
10
+ """
11
+ def decorator(func: Callable) -> Callable:
12
+ self._dp.add_listener(listeners.OnConnect(func))
13
+
14
+ return func
15
+
16
+ return decorator
@@ -0,0 +1,41 @@
1
+ from .services import *
2
+ from .listeners import *
3
+
4
+ CADATA = '''-----BEGIN CERTIFICATE-----
5
+ MIIESTCCAzGgAwIBAgIURvZnI5HhVeWWTrA8jjdZqmHsZDYwDQYJKoZIhvcNAQEL
6
+ BQAwgZkxCzAJBgNVBAYTAkNZMREwDwYDVQQIDAhMaW1hc3NvbDERMA8GA1UECgwI
7
+ QXhsZWJvbHQxDzANBgNVBAcMBkRldk9wczEeMBwGA1UEAwwVQ2VydGlmaWNhdGUg
8
+ QXV0aG9yaXR5MQ8wDQYDVQQLDAZEZXZPcHMxIjAgBgkqhkiG9w0BCQEWE2Rldm9w
9
+ c0BheGxlYm9sdC5jb20wHhcNMjQxMDIyMTEwNjQwWhcNMzQxMDEwMTEwNjQwWjCB
10
+ mTELMAkGA1UEBhMCQ1kxETAPBgNVBAgMCExpbWFzc29sMREwDwYDVQQKDAhBeGxl
11
+ Ym9sdDEPMA0GA1UEBwwGRGV2T3BzMR4wHAYDVQQDDBVDZXJ0aWZpY2F0ZSBBdXRo
12
+ b3JpdHkxDzANBgNVBAsMBkRldk9wczEiMCAGCSqGSIb3DQEJARYTZGV2b3BzQGF4
13
+ bGVib2x0LmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANKXifNv
14
+ kS2NOTTwnb4f2mfD2jO2mlG4RYmj1xwyDWaxhUSzJ7Jht2xX0t7M5V7rsnav5SAY
15
+ YaSzn70BKuR4KOhyKALl86kyYxdt83AaCAmAxikIlar4KFELM4XrsqzbebRt/tXS
16
+ eMBH4BV0gmE32xMG16s+N9kAp+NODktZQiOo/RVsCSdPtPFcxqq14kmjWjTYsO4A
17
+ rCRGp9e7GVLRf9KFN2U4YBFvDrDrWJzQEDTnNbyzhrBT1xBkLMim6fEY32TZ/NGm
18
+ pOG0qvZPceeIViMDxKsP0ufUduYycLDIGuitP3x46+l39w/Ti6VdHaUkCKmVk6W8
19
+ LHrVHcQ+IFZt4m8CAwEAAaOBhjCBgzAdBgNVHQ4EFgQU9Qhz93lF/mWhO7dXtjSU
20
+ lVjhA+owHwYDVR0jBBgwFoAU9Qhz93lF/mWhO7dXtjSUlVjhA+owEgYDVR0TAQH/
21
+ BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0lBBYwFAYIKwYBBQUHAwEG
22
+ CCsGAQUFBwMCMA0GCSqGSIb3DQEBCwUAA4IBAQCxAD5io1i7JdX0fuRgkwCVX435
23
+ ZgWSTwZdyIInZ5sstoVyJX7JsZiSVcqxdFWP8FFk5sxbkNL/TtoPoK5OWDXp9DtD
24
+ kNl+A7lgOMkpOdY8vKTGEk6yhSmOUENB2agP8VqMSB8VbLgpdV6/cgdeoDGJtG0z
25
+ GQu2t+x0cUfvY3aTpXAoj06fyFm2CAUyjzM6Ks1fqTDnl8MFnJ5Jen2xjGF+EFLd
26
+ daVqeKur2T039baj2qEMRIYHyOjf63yNPVU8r/mTG8wBm26lJzCx9ADIxGyW5KrJ
27
+ 8l8L2p6+gBAjubM6gQ3Dh5w4ydVRTUdgDVsMLE0pO9h3LQzuG3tye1hUWjtZ
28
+ -----END CERTIFICATE-----'''
29
+
30
+ class GeneratedServices:
31
+ raw = services
32
+
33
+ class Generated(
34
+ GeneratedServices,
35
+ GeneratedEvents
36
+ ): pass
37
+
38
+ __all__ = [
39
+ "CADATA",
40
+ Generated
41
+ ]