max-library 0.2.0__tar.gz → 0.4.0__tar.gz
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.
- {max_library-0.2.0/src/max_library.egg-info → max_library-0.4.0}/PKG-INFO +3 -1
- {max_library-0.2.0 → max_library-0.4.0}/pyproject.toml +3 -1
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/__init__.py +3 -1
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/client.py +83 -7
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/exceptions.py +6 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/models/chat.py +16 -1
- max_library-0.4.0/src/max_library/transport/__init__.py +7 -0
- max_library-0.4.0/src/max_library/transport/protocol.py +111 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/transport/websocket.py +65 -42
- {max_library-0.2.0 → max_library-0.4.0/src/max_library.egg-info}/PKG-INFO +3 -1
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library.egg-info/SOURCES.txt +2 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library.egg-info/requires.txt +2 -0
- {max_library-0.2.0 → max_library-0.4.0}/tests/test_client.py +75 -1
- {max_library-0.2.0 → max_library-0.4.0}/tests/test_models.py +22 -1
- max_library-0.4.0/tests/test_protocol.py +50 -0
- {max_library-0.2.0 → max_library-0.4.0}/tests/test_transport.py +17 -5
- max_library-0.2.0/src/max_library/transport/__init__.py +0 -6
- {max_library-0.2.0 → max_library-0.4.0}/LICENSE +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/README.md +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/setup.cfg +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/filters/__init__.py +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/filters/base.py +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/filters/builtin.py +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/models/__init__.py +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/models/attachment.py +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/models/base.py +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/models/contact.py +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/models/event.py +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/models/message.py +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/models/reaction.py +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library/models/user.py +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library.egg-info/dependency_links.txt +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/src/max_library.egg-info/top_level.txt +0 -0
- {max_library-0.2.0 → max_library-0.4.0}/tests/test_filters.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: max-library
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Async Python SDK for MAX Messenger protocol (web.oneme.ru / ws-api.oneme.ru)
|
|
5
5
|
Author: jirnobruh
|
|
6
6
|
License-Expression: MIT
|
|
@@ -23,6 +23,8 @@ License-File: LICENSE
|
|
|
23
23
|
Requires-Dist: websockets>=13.0
|
|
24
24
|
Requires-Dist: aiohttp>=3.9.0
|
|
25
25
|
Requires-Dist: pydantic>=2.0.0
|
|
26
|
+
Requires-Dist: msgpack>=1.0.0
|
|
27
|
+
Requires-Dist: lz4>=4.0.0
|
|
26
28
|
Provides-Extra: dev
|
|
27
29
|
Requires-Dist: pytest>=8.0.0; extra == "dev"
|
|
28
30
|
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "max-library"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.4.0"
|
|
8
8
|
description = "Async Python SDK for MAX Messenger protocol (web.oneme.ru / ws-api.oneme.ru)"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.10"
|
|
@@ -28,6 +28,8 @@ dependencies = [
|
|
|
28
28
|
"websockets>=13.0",
|
|
29
29
|
"aiohttp>=3.9.0",
|
|
30
30
|
"pydantic>=2.0.0",
|
|
31
|
+
"msgpack>=1.0.0",
|
|
32
|
+
"lz4>=4.0.0",
|
|
31
33
|
]
|
|
32
34
|
|
|
33
35
|
[project.optional-dependencies]
|
|
@@ -10,6 +10,7 @@ from max_library.exceptions import (
|
|
|
10
10
|
AuthError,
|
|
11
11
|
VerifyCodeWrong,
|
|
12
12
|
UserNotFoundError,
|
|
13
|
+
ChatNotFoundError,
|
|
13
14
|
)
|
|
14
15
|
from max_library.filters import filters, Filter
|
|
15
16
|
from max_library.models import (
|
|
@@ -26,7 +27,7 @@ from max_library.models import (
|
|
|
26
27
|
EMOJIS,
|
|
27
28
|
)
|
|
28
29
|
|
|
29
|
-
__version__ = "0.
|
|
30
|
+
__version__ = "0.4.0"
|
|
30
31
|
|
|
31
32
|
__all__ = [
|
|
32
33
|
"MaxClient",
|
|
@@ -39,6 +40,7 @@ __all__ = [
|
|
|
39
40
|
"AuthError",
|
|
40
41
|
"VerifyCodeWrong",
|
|
41
42
|
"UserNotFoundError",
|
|
43
|
+
"ChatNotFoundError",
|
|
42
44
|
"Attachment",
|
|
43
45
|
"Chat",
|
|
44
46
|
"Contact",
|
|
@@ -10,6 +10,7 @@ from uuid import uuid4
|
|
|
10
10
|
|
|
11
11
|
from max_library.exceptions import (
|
|
12
12
|
AuthError,
|
|
13
|
+
ChatNotFoundError,
|
|
13
14
|
MaxAPIError,
|
|
14
15
|
MaxConnectionError,
|
|
15
16
|
UserNotFoundError,
|
|
@@ -43,7 +44,7 @@ class MaxClient:
|
|
|
43
44
|
base_ws_url: str = DEFAULT_WS_URL,
|
|
44
45
|
auto_reconnect: bool = True,
|
|
45
46
|
num_workers: int = 4,
|
|
46
|
-
app_version: str = "
|
|
47
|
+
app_version: str = "26.11.9",
|
|
47
48
|
device_id: str | None = None,
|
|
48
49
|
heartbeat_interval: float = 45.0,
|
|
49
50
|
heartbeat_timeout: float = 120.0,
|
|
@@ -64,6 +65,7 @@ class MaxClient:
|
|
|
64
65
|
|
|
65
66
|
self.me: Optional[User] = None
|
|
66
67
|
self._is_running = False
|
|
68
|
+
self._chats_cache: dict[str, Chat] = {}
|
|
67
69
|
|
|
68
70
|
self._message_handlers: list[tuple[Optional[Filter | Callable], MessageHandler]] = []
|
|
69
71
|
self._connect_handlers: list[ConnectHandler] = []
|
|
@@ -237,14 +239,15 @@ class MaxClient:
|
|
|
237
239
|
payload = {
|
|
238
240
|
"userAgent": {
|
|
239
241
|
"deviceType": "WEB",
|
|
240
|
-
"
|
|
242
|
+
"pushDeviceType": "WEBPUSH",
|
|
243
|
+
"locale": "ru",
|
|
244
|
+
"deviceLocale": "ru",
|
|
241
245
|
"osVersion": "Windows",
|
|
242
|
-
"deviceName": "
|
|
243
|
-
"headerUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/
|
|
244
|
-
"deviceLocale": "en",
|
|
246
|
+
"deviceName": "Chrome",
|
|
247
|
+
"headerUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
|
|
245
248
|
"appVersion": self.app_version,
|
|
246
249
|
"screen": "1920x1080 1.0x",
|
|
247
|
-
"timezone": "
|
|
250
|
+
"timezone": "Europe/Moscow",
|
|
248
251
|
},
|
|
249
252
|
"deviceId": self.device_id,
|
|
250
253
|
}
|
|
@@ -275,6 +278,16 @@ class MaxClient:
|
|
|
275
278
|
user = User.model_validate(profile).bind_client(self)
|
|
276
279
|
self.me = user
|
|
277
280
|
logger.info(f"Authenticated as: {user.display_name} (ID: {user.id})")
|
|
281
|
+
|
|
282
|
+
# Cache initial chats returned in session payload
|
|
283
|
+
raw_chats = resp_payload.get("chats", [])
|
|
284
|
+
for raw_chat in raw_chats:
|
|
285
|
+
try:
|
|
286
|
+
chat_obj = Chat.model_validate(raw_chat).bind_client(self)
|
|
287
|
+
self._chats_cache[str(chat_obj.id)] = chat_obj
|
|
288
|
+
except Exception as e:
|
|
289
|
+
logger.debug(f"Failed to parse initial chat from session: {e}")
|
|
290
|
+
|
|
278
291
|
return user
|
|
279
292
|
|
|
280
293
|
async def _restore_session_on_reconnect(self) -> None:
|
|
@@ -623,9 +636,72 @@ class MaxClient:
|
|
|
623
636
|
return True
|
|
624
637
|
|
|
625
638
|
# =========================================================================
|
|
626
|
-
# Chat Actions (Opcode 22, 20)
|
|
639
|
+
# Chat Actions (Opcode 48, 19, 22, 20)
|
|
627
640
|
# =========================================================================
|
|
628
641
|
|
|
642
|
+
async def get_chats(self, count: int = 40, force_refresh: bool = False) -> list[Chat]:
|
|
643
|
+
"""
|
|
644
|
+
Retrieves list of user chats. Returns cached list from session init unless force_refresh is True.
|
|
645
|
+
"""
|
|
646
|
+
if not force_refresh and self._chats_cache:
|
|
647
|
+
return list(self._chats_cache.values())
|
|
648
|
+
|
|
649
|
+
if not self.token:
|
|
650
|
+
raise ValueError("No auth token provided. Authenticate first.")
|
|
651
|
+
|
|
652
|
+
resp = await self.transport.send_request(
|
|
653
|
+
opcode=19,
|
|
654
|
+
payload={
|
|
655
|
+
"interactive": True,
|
|
656
|
+
"token": self.token,
|
|
657
|
+
"chatsSync": 0,
|
|
658
|
+
"contactsSync": 0,
|
|
659
|
+
"presenceSync": 0,
|
|
660
|
+
"draftsSync": 0,
|
|
661
|
+
"chatsCount": count,
|
|
662
|
+
},
|
|
663
|
+
)
|
|
664
|
+
chats_data = resp.get("payload", {}).get("chats", [])
|
|
665
|
+
chats: list[Chat] = []
|
|
666
|
+
for raw in chats_data:
|
|
667
|
+
chat = Chat.model_validate(raw).bind_client(self)
|
|
668
|
+
self._chats_cache[str(chat.id)] = chat
|
|
669
|
+
chats.append(chat)
|
|
670
|
+
return chats
|
|
671
|
+
|
|
672
|
+
async def get_chat(self, chat_id: int | str, force_refresh: bool = False) -> Chat:
|
|
673
|
+
"""
|
|
674
|
+
Retrieves detailed chat information by chat ID (Opcode 48).
|
|
675
|
+
Uses internal session cache unless force_refresh is True.
|
|
676
|
+
"""
|
|
677
|
+
key = str(chat_id).strip()
|
|
678
|
+
if not force_refresh and key in self._chats_cache:
|
|
679
|
+
return self._chats_cache[key]
|
|
680
|
+
|
|
681
|
+
cid = int(chat_id) if str(chat_id).lstrip("-").isdigit() else chat_id
|
|
682
|
+
resp = await self.transport.send_request(
|
|
683
|
+
opcode=48,
|
|
684
|
+
payload={"chatIds": [cid]},
|
|
685
|
+
)
|
|
686
|
+
chats_data = resp.get("payload", {}).get("chats", [])
|
|
687
|
+
if not chats_data:
|
|
688
|
+
raise ChatNotFoundError(error="chat.not.found", message=f"Chat {chat_id} not found")
|
|
689
|
+
|
|
690
|
+
chat = Chat.model_validate(chats_data[0]).bind_client(self)
|
|
691
|
+
|
|
692
|
+
# For DIALOG chats without explicit title, resolve interlocutor name if possible
|
|
693
|
+
if not chat.title and chat.type == "DIALOG" and isinstance(chat.participants, dict) and self.me:
|
|
694
|
+
other_ids = [uid for uid in chat.participants if str(uid) != str(self.me.id)]
|
|
695
|
+
if other_ids:
|
|
696
|
+
try:
|
|
697
|
+
other_user = await self.get_user(id=other_ids[0])
|
|
698
|
+
chat.title = other_user.display_name
|
|
699
|
+
except Exception as e:
|
|
700
|
+
logger.debug(f"Could not resolve interlocutor for dialog {chat_id}: {e}")
|
|
701
|
+
|
|
702
|
+
self._chats_cache[key] = chat
|
|
703
|
+
return chat
|
|
704
|
+
|
|
629
705
|
async def pin_chat(self, chat_id: int | str) -> bool:
|
|
630
706
|
"""Pins a chat (Opcode 22)."""
|
|
631
707
|
await self.transport.send_request(
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
"""
|
|
2
2
|
Chat model for MAX.
|
|
3
3
|
"""
|
|
4
4
|
from typing import Any
|
|
@@ -12,11 +12,26 @@ class Chat(MaxBaseModel):
|
|
|
12
12
|
"""
|
|
13
13
|
id: int | str
|
|
14
14
|
title: str | None = None
|
|
15
|
+
type: str | None = None
|
|
16
|
+
description: str | None = None
|
|
15
17
|
link: str | None = None
|
|
18
|
+
participants_count: int | None = Field(default=None, alias="participantsCount")
|
|
19
|
+
participants: dict[str, Any] | list[Any] | None = None
|
|
20
|
+
owner: int | str | None = None
|
|
21
|
+
base_icon_url: str | None = Field(default=None, alias="baseIconUrl")
|
|
22
|
+
base_raw_icon_url: str | None = Field(default=None, alias="baseRawIconUrl")
|
|
23
|
+
status: str | None = None
|
|
16
24
|
messages: list[Any] = Field(default_factory=list)
|
|
17
25
|
|
|
18
26
|
_client: Any = PrivateAttr(default=None)
|
|
19
27
|
|
|
28
|
+
@property
|
|
29
|
+
def display_name(self) -> str:
|
|
30
|
+
"""Returns the title of the chat, or a formatted fallback identifier."""
|
|
31
|
+
if self.title and self.title.strip():
|
|
32
|
+
return self.title.strip()
|
|
33
|
+
return f"Чат {self.id}"
|
|
34
|
+
|
|
20
35
|
def bind_client(self, client: Any) -> "Chat":
|
|
21
36
|
self._client = client
|
|
22
37
|
return self
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Transport layer for max-client.
|
|
3
|
+
"""
|
|
4
|
+
from max_library.transport.websocket import MaxTransport, DEFAULT_WS_URL, DEFAULT_HEADERS
|
|
5
|
+
from max_library.transport.protocol import encode_packet, decode_packet
|
|
6
|
+
|
|
7
|
+
__all__ = ["MaxTransport", "DEFAULT_WS_URL", "DEFAULT_HEADERS", "encode_packet", "decode_packet"]
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Binary protocol packet encoder/decoder for MAX Messenger (Proto version 10).
|
|
3
|
+
Uses msgpack for payload serialization and optional lz4 block compression.
|
|
4
|
+
"""
|
|
5
|
+
import struct
|
|
6
|
+
from typing import Any, Tuple, Optional
|
|
7
|
+
import msgpack
|
|
8
|
+
import lz4.block
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
HEADER_LENGTH = 10
|
|
12
|
+
PROTO_VERSION = 10
|
|
13
|
+
MIN_COMPRESS_LENGTH = 32 # jC in MAX client source
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def ext_hook(code: int, data: bytes) -> Any:
|
|
17
|
+
"""
|
|
18
|
+
Handles MsgPack Extension types.
|
|
19
|
+
Extension type 1 is used by MAX for 64-bit / BigInt values (e.g. user IDs, chat IDs, message IDs).
|
|
20
|
+
"""
|
|
21
|
+
if code == 1:
|
|
22
|
+
# ExtType 1 contains msgpack-encoded int/bigint
|
|
23
|
+
return msgpack.unpackb(data, raw=False)
|
|
24
|
+
return msgpack.ExtType(code, data)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def encode_packet(
|
|
28
|
+
cmd: int,
|
|
29
|
+
seq: int,
|
|
30
|
+
opcode: int,
|
|
31
|
+
payload: Any = None,
|
|
32
|
+
compress: bool = False,
|
|
33
|
+
) -> bytes:
|
|
34
|
+
"""
|
|
35
|
+
Encodes a MAX protocol binary packet.
|
|
36
|
+
|
|
37
|
+
Header structure (10 bytes):
|
|
38
|
+
Byte 0: Proto version (10)
|
|
39
|
+
Byte 1: Command type (0: request, 1: response, 2: cancel, 3: ack/error)
|
|
40
|
+
Bytes 2..3: Sequence number (int16 big-endian)
|
|
41
|
+
Bytes 4..5: Opcode (int16 big-endian)
|
|
42
|
+
Byte 6: Compression ratio factor (0 if uncompressed)
|
|
43
|
+
Bytes 7..9: 24-bit payload byte length (big-endian)
|
|
44
|
+
"""
|
|
45
|
+
if payload is not None:
|
|
46
|
+
payload_bytes = msgpack.packb(payload, use_bin_type=True)
|
|
47
|
+
else:
|
|
48
|
+
payload_bytes = b""
|
|
49
|
+
|
|
50
|
+
comp_factor = 0
|
|
51
|
+
if compress and len(payload_bytes) > MIN_COMPRESS_LENGTH:
|
|
52
|
+
compressed = lz4.block.compress(payload_bytes, store_size=False)
|
|
53
|
+
if len(compressed) < len(payload_bytes):
|
|
54
|
+
factor = min(int((len(payload_bytes) + len(compressed) - 1) // len(compressed)), 255)
|
|
55
|
+
if factor > 0:
|
|
56
|
+
payload_bytes = compressed
|
|
57
|
+
comp_factor = factor
|
|
58
|
+
|
|
59
|
+
length = len(payload_bytes)
|
|
60
|
+
header = bytearray(HEADER_LENGTH)
|
|
61
|
+
header[0] = PROTO_VERSION
|
|
62
|
+
header[1] = cmd & 0xFF
|
|
63
|
+
struct.pack_into(">h", header, 2, seq)
|
|
64
|
+
struct.pack_into(">h", header, 4, opcode)
|
|
65
|
+
header[6] = comp_factor & 0xFF
|
|
66
|
+
header[7] = (length >> 16) & 0xFF
|
|
67
|
+
header[8] = (length >> 8) & 0xFF
|
|
68
|
+
header[9] = length & 0xFF
|
|
69
|
+
|
|
70
|
+
return bytes(header) + payload_bytes
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def decode_packet(data: bytes) -> dict[str, Any]:
|
|
74
|
+
"""
|
|
75
|
+
Decodes a MAX protocol binary packet from bytes.
|
|
76
|
+
"""
|
|
77
|
+
if len(data) < HEADER_LENGTH:
|
|
78
|
+
raise ValueError(f"Packet too short: {len(data)} bytes (expected >= {HEADER_LENGTH})")
|
|
79
|
+
|
|
80
|
+
proto = data[0]
|
|
81
|
+
cmd = data[1]
|
|
82
|
+
seq, opcode = struct.unpack_from(">hh", data, 2)
|
|
83
|
+
comp_factor = data[6]
|
|
84
|
+
length = (data[7] << 16) | (data[8] << 8) | data[9]
|
|
85
|
+
|
|
86
|
+
if len(data) < HEADER_LENGTH + length:
|
|
87
|
+
raise ValueError(f"Packet payload truncated: got {len(data) - HEADER_LENGTH}, expected {length}")
|
|
88
|
+
|
|
89
|
+
payload_bytes = data[HEADER_LENGTH : HEADER_LENGTH + length]
|
|
90
|
+
|
|
91
|
+
if comp_factor > 0 and payload_bytes:
|
|
92
|
+
uncompressed_size = length * comp_factor
|
|
93
|
+
payload_bytes = lz4.block.decompress(payload_bytes, uncompressed_size=uncompressed_size)
|
|
94
|
+
|
|
95
|
+
if payload_bytes:
|
|
96
|
+
payload = msgpack.unpackb(
|
|
97
|
+
payload_bytes,
|
|
98
|
+
raw=False,
|
|
99
|
+
strict_map_key=False,
|
|
100
|
+
ext_hook=ext_hook,
|
|
101
|
+
)
|
|
102
|
+
else:
|
|
103
|
+
payload = None
|
|
104
|
+
|
|
105
|
+
return {
|
|
106
|
+
"ver": proto,
|
|
107
|
+
"cmd": cmd,
|
|
108
|
+
"seq": seq,
|
|
109
|
+
"opcode": opcode,
|
|
110
|
+
"payload": payload,
|
|
111
|
+
}
|
|
@@ -24,17 +24,19 @@ from max_library.exceptions import (
|
|
|
24
24
|
AuthError,
|
|
25
25
|
VerifyCodeWrong,
|
|
26
26
|
UserNotFoundError,
|
|
27
|
+
ChatNotFoundError,
|
|
27
28
|
)
|
|
28
29
|
from max_library.models.event import IncomingEvent
|
|
30
|
+
from max_library.transport.protocol import encode_packet, decode_packet
|
|
29
31
|
|
|
30
32
|
logger = logging.getLogger("max_library.transport")
|
|
31
33
|
|
|
32
|
-
DEFAULT_WS_URL = "wss://
|
|
34
|
+
DEFAULT_WS_URL = "wss://api.oneme.ru/websocket"
|
|
33
35
|
DEFAULT_HEADERS = {
|
|
34
|
-
"Origin": "https://web.
|
|
36
|
+
"Origin": "https://web.max.ru",
|
|
35
37
|
"Pragma": "no-cache",
|
|
36
38
|
"Cache-Control": "no-cache",
|
|
37
|
-
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/
|
|
39
|
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
|
|
38
40
|
}
|
|
39
41
|
|
|
40
42
|
|
|
@@ -202,25 +204,57 @@ class MaxTransport:
|
|
|
202
204
|
async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:
|
|
203
205
|
await self.close()
|
|
204
206
|
|
|
205
|
-
async def
|
|
206
|
-
|
|
207
|
+
async def send_packet(
|
|
208
|
+
self,
|
|
209
|
+
cmd: int,
|
|
210
|
+
seq: int,
|
|
211
|
+
opcode: int,
|
|
212
|
+
payload: Any = None,
|
|
213
|
+
compress: bool = False,
|
|
214
|
+
) -> None:
|
|
215
|
+
"""Sends a binary-encoded MAX protocol frame over the active WebSocket."""
|
|
207
216
|
if not self.is_connected or not self._ws:
|
|
208
217
|
raise MaxConnectionError("Cannot send frame: WebSocket is not connected")
|
|
209
218
|
|
|
210
|
-
|
|
211
|
-
logger.debug(f"WS SEND: {
|
|
219
|
+
packet_bytes = encode_packet(cmd=cmd, seq=seq, opcode=opcode, payload=payload, compress=compress)
|
|
220
|
+
logger.debug(f"WS SEND: cmd={cmd}, seq={seq}, opcode={opcode}, len={len(packet_bytes)}")
|
|
212
221
|
async with self._send_lock:
|
|
213
222
|
if not self.is_connected or not self._ws:
|
|
214
223
|
raise MaxConnectionError("Cannot send frame: WebSocket is not connected")
|
|
215
|
-
await self._ws.send(
|
|
224
|
+
await self._ws.send(packet_bytes)
|
|
216
225
|
|
|
217
|
-
async def
|
|
218
|
-
|
|
226
|
+
async def _safe_send_packet(
|
|
227
|
+
self,
|
|
228
|
+
cmd: int,
|
|
229
|
+
seq: int,
|
|
230
|
+
opcode: int,
|
|
231
|
+
payload: Any = None,
|
|
232
|
+
compress: bool = False,
|
|
233
|
+
) -> None:
|
|
234
|
+
"""Sends a binary frame safely in background, logging errors without raising."""
|
|
219
235
|
try:
|
|
220
|
-
await self.
|
|
236
|
+
await self.send_packet(cmd=cmd, seq=seq, opcode=opcode, payload=payload, compress=compress)
|
|
221
237
|
except Exception as e:
|
|
222
238
|
logger.debug(f"Failed to send background frame: {e}")
|
|
223
239
|
|
|
240
|
+
# Backward-compatible alias for existing tests/callers
|
|
241
|
+
async def send_raw_json(self, data: dict[str, Any]) -> None:
|
|
242
|
+
"""Sends a frame over WebSocket (encodes to binary protocol)."""
|
|
243
|
+
cmd = data.get("cmd", 0)
|
|
244
|
+
seq = data.get("seq", 0)
|
|
245
|
+
opcode = data.get("opcode", 0)
|
|
246
|
+
payload = data.get("payload")
|
|
247
|
+
await self.send_packet(cmd=cmd, seq=seq, opcode=opcode, payload=payload)
|
|
248
|
+
|
|
249
|
+
async def _safe_send_raw_json(self, data: dict[str, Any]) -> None:
|
|
250
|
+
"""Safely sends a frame over WebSocket."""
|
|
251
|
+
await self._safe_send_packet(
|
|
252
|
+
cmd=data.get("cmd", 0),
|
|
253
|
+
seq=data.get("seq", 0),
|
|
254
|
+
opcode=data.get("opcode", 0),
|
|
255
|
+
payload=data.get("payload"),
|
|
256
|
+
)
|
|
257
|
+
|
|
224
258
|
async def send_request(
|
|
225
259
|
self,
|
|
226
260
|
opcode: int,
|
|
@@ -239,16 +273,8 @@ class MaxTransport:
|
|
|
239
273
|
future: asyncio.Future[dict[str, Any]] = loop.create_future()
|
|
240
274
|
self._pending_requests[seq] = future
|
|
241
275
|
|
|
242
|
-
frame = {
|
|
243
|
-
"ver": 11,
|
|
244
|
-
"cmd": 0,
|
|
245
|
-
"seq": seq,
|
|
246
|
-
"opcode": opcode,
|
|
247
|
-
"payload": payload,
|
|
248
|
-
}
|
|
249
|
-
|
|
250
276
|
try:
|
|
251
|
-
await self.
|
|
277
|
+
await self.send_packet(cmd=0, seq=seq, opcode=opcode, payload=payload)
|
|
252
278
|
response = await asyncio.wait_for(future, timeout=timeout)
|
|
253
279
|
except asyncio.TimeoutError as e:
|
|
254
280
|
logger.warning(f"RPC request timeout: opcode={opcode}, seq={seq}")
|
|
@@ -266,12 +292,13 @@ class MaxTransport:
|
|
|
266
292
|
@staticmethod
|
|
267
293
|
def _check_response_error(response: dict[str, Any], opcode: int) -> None:
|
|
268
294
|
"""Inspects response frame and raises mapped exception if server returned error."""
|
|
295
|
+
cmd = response.get("cmd")
|
|
269
296
|
payload = response.get("payload", {})
|
|
270
297
|
if not isinstance(payload, dict):
|
|
271
298
|
return
|
|
272
299
|
|
|
273
300
|
error = payload.get("error")
|
|
274
|
-
if not error:
|
|
301
|
+
if not error and cmd != 3:
|
|
275
302
|
return
|
|
276
303
|
|
|
277
304
|
title = payload.get("title")
|
|
@@ -283,10 +310,12 @@ class MaxTransport:
|
|
|
283
310
|
raise VerifyCodeWrong(error=error, title=title, message=message, payload=payload, raw_response=response)
|
|
284
311
|
if error in ("auth.error", "token.invalid", "session.not_found"):
|
|
285
312
|
raise AuthError(error=error, title=title, message=message, payload=payload, raw_response=response)
|
|
286
|
-
if "user.not.found" in error or error == "contact.not.found":
|
|
313
|
+
if error and ("user.not.found" in error or error == "contact.not.found"):
|
|
287
314
|
raise UserNotFoundError(error=error, title=title, message=message, payload=payload, raw_response=response)
|
|
315
|
+
if error and "chat.not.found" in error:
|
|
316
|
+
raise ChatNotFoundError(error=error, title=title, message=message, payload=payload, raw_response=response)
|
|
288
317
|
|
|
289
|
-
raise MaxAPIError(error=error, title=title, message=message, payload=payload, raw_response=response)
|
|
318
|
+
raise MaxAPIError(error=error or "unknown_error", title=title, message=message, payload=payload, raw_response=response)
|
|
290
319
|
|
|
291
320
|
async def _read_loop(self) -> None:
|
|
292
321
|
"""Continuous background loop for receiving and dispatching frames."""
|
|
@@ -307,9 +336,15 @@ class MaxTransport:
|
|
|
307
336
|
continue
|
|
308
337
|
|
|
309
338
|
try:
|
|
310
|
-
|
|
339
|
+
if isinstance(raw_msg, bytes):
|
|
340
|
+
data = decode_packet(raw_msg)
|
|
341
|
+
elif isinstance(raw_msg, str):
|
|
342
|
+
data = json.loads(raw_msg)
|
|
343
|
+
else:
|
|
344
|
+
logger.warning(f"Unknown frame type: {type(raw_msg)}")
|
|
345
|
+
continue
|
|
311
346
|
except Exception as e:
|
|
312
|
-
logger.warning(f"Failed to parse
|
|
347
|
+
logger.warning(f"Failed to parse frame: {raw_msg!r}, error: {e}")
|
|
313
348
|
continue
|
|
314
349
|
|
|
315
350
|
self._last_received_time = time.monotonic()
|
|
@@ -343,16 +378,11 @@ class MaxTransport:
|
|
|
343
378
|
if opcode == 1:
|
|
344
379
|
cmd = data.get("cmd")
|
|
345
380
|
if cmd == 0:
|
|
346
|
-
# Server sent a ping -> respond with pong immediately
|
|
347
|
-
pong_frame = {
|
|
348
|
-
"ver": 11,
|
|
349
|
-
"cmd": 1,
|
|
350
|
-
"seq": seq if seq is not None else 0,
|
|
351
|
-
"opcode": 1,
|
|
352
|
-
"payload": None,
|
|
353
|
-
}
|
|
381
|
+
# Server sent a ping -> respond with pong immediately (cmd 1, opcode 1)
|
|
354
382
|
logger.debug(f"Responding to MAX server heartbeat ping (seq={seq})")
|
|
355
|
-
asyncio.create_task(
|
|
383
|
+
asyncio.create_task(
|
|
384
|
+
self._safe_send_packet(cmd=1, seq=seq if seq is not None else 0, opcode=1, payload=None)
|
|
385
|
+
)
|
|
356
386
|
return
|
|
357
387
|
|
|
358
388
|
# 3. Push event (opcode 128 for messages, or other server pushes)
|
|
@@ -394,15 +424,8 @@ class MaxTransport:
|
|
|
394
424
|
# 2. Idle timeout: send proactive client heartbeat (opcode 1, cmd 0)
|
|
395
425
|
if idle_time >= self.heartbeat_interval:
|
|
396
426
|
seq = await self.next_seq()
|
|
397
|
-
ping_frame = {
|
|
398
|
-
"ver": 11,
|
|
399
|
-
"cmd": 0,
|
|
400
|
-
"seq": seq,
|
|
401
|
-
"opcode": 1,
|
|
402
|
-
"payload": None,
|
|
403
|
-
}
|
|
404
427
|
logger.debug(f"Sending client application heartbeat ping (seq={seq}, idle={idle_time:.1f}s)")
|
|
405
|
-
await self.
|
|
428
|
+
await self._safe_send_packet(cmd=0, seq=seq, opcode=1, payload=None)
|
|
406
429
|
|
|
407
430
|
except asyncio.CancelledError:
|
|
408
431
|
pass
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: max-library
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Async Python SDK for MAX Messenger protocol (web.oneme.ru / ws-api.oneme.ru)
|
|
5
5
|
Author: jirnobruh
|
|
6
6
|
License-Expression: MIT
|
|
@@ -23,6 +23,8 @@ License-File: LICENSE
|
|
|
23
23
|
Requires-Dist: websockets>=13.0
|
|
24
24
|
Requires-Dist: aiohttp>=3.9.0
|
|
25
25
|
Requires-Dist: pydantic>=2.0.0
|
|
26
|
+
Requires-Dist: msgpack>=1.0.0
|
|
27
|
+
Requires-Dist: lz4>=4.0.0
|
|
26
28
|
Provides-Extra: dev
|
|
27
29
|
Requires-Dist: pytest>=8.0.0; extra == "dev"
|
|
28
30
|
Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
|
|
@@ -22,8 +22,10 @@ src/max_library/models/message.py
|
|
|
22
22
|
src/max_library/models/reaction.py
|
|
23
23
|
src/max_library/models/user.py
|
|
24
24
|
src/max_library/transport/__init__.py
|
|
25
|
+
src/max_library/transport/protocol.py
|
|
25
26
|
src/max_library/transport/websocket.py
|
|
26
27
|
tests/test_client.py
|
|
27
28
|
tests/test_filters.py
|
|
28
29
|
tests/test_models.py
|
|
30
|
+
tests/test_protocol.py
|
|
29
31
|
tests/test_transport.py
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
"""
|
|
2
2
|
Unit tests for high-level MaxClient operations and message handling.
|
|
3
3
|
"""
|
|
4
4
|
import asyncio
|
|
@@ -168,3 +168,77 @@ async def test_client_auth_flow():
|
|
|
168
168
|
assert client.me.id == 9999
|
|
169
169
|
|
|
170
170
|
await client.close()
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
@pytest.mark.asyncio
|
|
174
|
+
async def test_client_get_chat():
|
|
175
|
+
from max_library.exceptions import ChatNotFoundError
|
|
176
|
+
from max_library.models import Chat
|
|
177
|
+
|
|
178
|
+
client = MaxClient(token="test_token")
|
|
179
|
+
mock_send = AsyncMock(return_value={
|
|
180
|
+
"ver": 11,
|
|
181
|
+
"opcode": 48,
|
|
182
|
+
"payload": {
|
|
183
|
+
"chats": [
|
|
184
|
+
{
|
|
185
|
+
"id": -100500,
|
|
186
|
+
"title": "General Discussion",
|
|
187
|
+
"type": "CHAT",
|
|
188
|
+
"participantsCount": 15,
|
|
189
|
+
}
|
|
190
|
+
]
|
|
191
|
+
},
|
|
192
|
+
})
|
|
193
|
+
client.transport.send_request = mock_send
|
|
194
|
+
client.transport._is_connected = True
|
|
195
|
+
|
|
196
|
+
chat = await client.get_chat(-100500)
|
|
197
|
+
assert isinstance(chat, Chat)
|
|
198
|
+
assert chat.id == -100500
|
|
199
|
+
assert chat.title == "General Discussion"
|
|
200
|
+
assert chat.display_name == "General Discussion"
|
|
201
|
+
assert mock_send.call_count == 1
|
|
202
|
+
|
|
203
|
+
# Second call should hit the cache without calling transport
|
|
204
|
+
cached_chat = await client.get_chat("-100500")
|
|
205
|
+
assert cached_chat.title == "General Discussion"
|
|
206
|
+
assert mock_send.call_count == 1
|
|
207
|
+
|
|
208
|
+
# Force refresh should call transport again
|
|
209
|
+
refreshed_chat = await client.get_chat("-100500", force_refresh=True)
|
|
210
|
+
assert refreshed_chat.title == "General Discussion"
|
|
211
|
+
assert mock_send.call_count == 2
|
|
212
|
+
|
|
213
|
+
# Not found case
|
|
214
|
+
mock_send.return_value = {"ver": 11, "opcode": 48, "payload": {"chats": []}}
|
|
215
|
+
with pytest.raises(ChatNotFoundError):
|
|
216
|
+
await client.get_chat(999999)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
@pytest.mark.asyncio
|
|
220
|
+
async def test_client_get_chats_and_session_caching():
|
|
221
|
+
client = MaxClient(token="test_token")
|
|
222
|
+
# Simulate session init with 2 chats
|
|
223
|
+
client._chats_cache = {}
|
|
224
|
+
mock_send = AsyncMock(return_value={
|
|
225
|
+
"ver": 11,
|
|
226
|
+
"opcode": 19,
|
|
227
|
+
"payload": {
|
|
228
|
+
"profile": {"id": 1, "names": [{"name": "Owner"}]},
|
|
229
|
+
"chats": [
|
|
230
|
+
{"id": 101, "title": "Project Alpha", "type": "CHAT"},
|
|
231
|
+
{"id": 102, "title": "Project Beta", "type": "CHAT"},
|
|
232
|
+
],
|
|
233
|
+
},
|
|
234
|
+
})
|
|
235
|
+
client.transport.send_request = mock_send
|
|
236
|
+
client.transport._is_connected = True
|
|
237
|
+
|
|
238
|
+
chats = await client.get_chats(force_refresh=True)
|
|
239
|
+
assert len(chats) == 2
|
|
240
|
+
assert chats[0].title == "Project Alpha"
|
|
241
|
+
assert chats[1].title == "Project Beta"
|
|
242
|
+
assert "101" in client._chats_cache
|
|
243
|
+
assert "102" in client._chats_cache
|
|
244
|
+
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
"""
|
|
2
2
|
Tests for Pydantic models serialization and deserialization.
|
|
3
3
|
"""
|
|
4
4
|
from max_library.models import (
|
|
@@ -154,3 +154,24 @@ def test_incoming_event_model():
|
|
|
154
154
|
assert event.seq == 42
|
|
155
155
|
assert event.opcode == 128
|
|
156
156
|
assert event.payload["chatId"] == 12345
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def test_chat_model():
|
|
160
|
+
data = {
|
|
161
|
+
"id": -69130574105108,
|
|
162
|
+
"title": "Рабочий чат",
|
|
163
|
+
"type": "CHAT",
|
|
164
|
+
"participantsCount": 10,
|
|
165
|
+
"baseIconUrl": "https://img.oneme.ru/icon/chat.jpg",
|
|
166
|
+
"description": "Описание рабочего чата",
|
|
167
|
+
}
|
|
168
|
+
chat = Chat.model_validate(data)
|
|
169
|
+
assert chat.id == -69130574105108
|
|
170
|
+
assert chat.title == "Рабочий чат"
|
|
171
|
+
assert chat.display_name == "Рабочий чат"
|
|
172
|
+
assert chat.type == "CHAT"
|
|
173
|
+
assert chat.participants_count == 10
|
|
174
|
+
|
|
175
|
+
# Fallback display name when title is None
|
|
176
|
+
chat_empty = Chat(id=12345)
|
|
177
|
+
assert chat_empty.display_name == "Чат 12345"
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Unit tests for binary protocol encoding and decoding (v10).
|
|
3
|
+
"""
|
|
4
|
+
import pytest
|
|
5
|
+
from max_library.transport.protocol import encode_packet, decode_packet, ext_hook
|
|
6
|
+
import msgpack
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def test_encode_and_decode_simple_packet():
|
|
10
|
+
payload = {"hello": "world", "num": 123}
|
|
11
|
+
encoded = encode_packet(cmd=0, seq=42, opcode=6, payload=payload)
|
|
12
|
+
assert len(encoded) >= 10
|
|
13
|
+
assert encoded[0] == 10 # Proto version 10
|
|
14
|
+
assert encoded[1] == 0 # cmd
|
|
15
|
+
|
|
16
|
+
decoded = decode_packet(encoded)
|
|
17
|
+
assert decoded["ver"] == 10
|
|
18
|
+
assert decoded["cmd"] == 0
|
|
19
|
+
assert decoded["seq"] == 42
|
|
20
|
+
assert decoded["opcode"] == 6
|
|
21
|
+
assert decoded["payload"] == payload
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def test_encode_and_decode_none_payload():
|
|
25
|
+
encoded = encode_packet(cmd=1, seq=100, opcode=1, payload=None)
|
|
26
|
+
assert len(encoded) == 10
|
|
27
|
+
decoded = decode_packet(encoded)
|
|
28
|
+
assert decoded["cmd"] == 1
|
|
29
|
+
assert decoded["seq"] == 100
|
|
30
|
+
assert decoded["opcode"] == 1
|
|
31
|
+
assert decoded["payload"] is None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_encode_and_decode_compressed_packet():
|
|
35
|
+
# Long repetitive payload to ensure compression triggers
|
|
36
|
+
payload = {"long_text": "A" * 1000, "list": list(range(100))}
|
|
37
|
+
encoded = encode_packet(cmd=0, seq=7, opcode=19, payload=payload, compress=True)
|
|
38
|
+
# Check that compression factor > 0
|
|
39
|
+
comp_factor = encoded[6]
|
|
40
|
+
assert comp_factor > 0
|
|
41
|
+
|
|
42
|
+
decoded = decode_packet(encoded)
|
|
43
|
+
assert decoded["payload"] == payload
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_decode_ext_type_1():
|
|
47
|
+
# ExtType 1 is used for BigInt / ID numbers
|
|
48
|
+
packed_val = msgpack.packb(64768666)
|
|
49
|
+
res = ext_hook(1, packed_val)
|
|
50
|
+
assert res == 64768666
|
|
@@ -9,25 +9,37 @@ from max_library.exceptions import MaxAPIError, MaxTimeoutError, VerifyCodeWrong
|
|
|
9
9
|
from max_library.transport.websocket import MaxTransport
|
|
10
10
|
|
|
11
11
|
|
|
12
|
+
from max_library.transport.protocol import encode_packet, decode_packet
|
|
13
|
+
|
|
14
|
+
|
|
12
15
|
class MockWebSocket:
|
|
13
16
|
"""Mock WebSocket client connection simulating duplex async frames."""
|
|
14
17
|
|
|
15
18
|
def __init__(self):
|
|
16
19
|
self.sent_frames: list[dict] = []
|
|
17
|
-
self.recv_queue: asyncio.Queue[str] = asyncio.Queue()
|
|
20
|
+
self.recv_queue: asyncio.Queue[bytes | str] = asyncio.Queue()
|
|
18
21
|
self.is_closed = False
|
|
19
22
|
|
|
20
|
-
async def send(self, data: str):
|
|
21
|
-
|
|
23
|
+
async def send(self, data: bytes | str):
|
|
24
|
+
if isinstance(data, bytes):
|
|
25
|
+
self.sent_frames.append(decode_packet(data))
|
|
26
|
+
else:
|
|
27
|
+
self.sent_frames.append(json.loads(data))
|
|
22
28
|
|
|
23
|
-
async def recv(self) -> str:
|
|
29
|
+
async def recv(self) -> bytes | str:
|
|
24
30
|
return await self.recv_queue.get()
|
|
25
31
|
|
|
26
32
|
async def close(self):
|
|
27
33
|
self.is_closed = True
|
|
28
34
|
|
|
29
35
|
def put_incoming(self, frame_dict: dict):
|
|
30
|
-
|
|
36
|
+
# Convert dictionary to binary packet format
|
|
37
|
+
cmd = frame_dict.get("cmd", 0)
|
|
38
|
+
seq = frame_dict.get("seq", 0)
|
|
39
|
+
opcode = frame_dict.get("opcode", 0)
|
|
40
|
+
payload = frame_dict.get("payload")
|
|
41
|
+
packet_bytes = encode_packet(cmd=cmd, seq=seq, opcode=opcode, payload=payload)
|
|
42
|
+
self.recv_queue.put_nowait(packet_bytes)
|
|
31
43
|
|
|
32
44
|
|
|
33
45
|
@pytest.fixture
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|