max-library 0.2.0__tar.gz → 0.3.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.
Files changed (31) hide show
  1. {max_library-0.2.0/src/max_library.egg-info → max_library-0.3.0}/PKG-INFO +1 -1
  2. {max_library-0.2.0 → max_library-0.3.0}/pyproject.toml +1 -1
  3. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/__init__.py +3 -1
  4. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/client.py +76 -1
  5. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/exceptions.py +6 -0
  6. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/models/chat.py +16 -1
  7. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/transport/websocket.py +3 -0
  8. {max_library-0.2.0 → max_library-0.3.0/src/max_library.egg-info}/PKG-INFO +1 -1
  9. {max_library-0.2.0 → max_library-0.3.0}/tests/test_client.py +75 -1
  10. {max_library-0.2.0 → max_library-0.3.0}/tests/test_models.py +22 -1
  11. {max_library-0.2.0 → max_library-0.3.0}/LICENSE +0 -0
  12. {max_library-0.2.0 → max_library-0.3.0}/README.md +0 -0
  13. {max_library-0.2.0 → max_library-0.3.0}/setup.cfg +0 -0
  14. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/filters/__init__.py +0 -0
  15. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/filters/base.py +0 -0
  16. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/filters/builtin.py +0 -0
  17. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/models/__init__.py +0 -0
  18. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/models/attachment.py +0 -0
  19. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/models/base.py +0 -0
  20. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/models/contact.py +0 -0
  21. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/models/event.py +0 -0
  22. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/models/message.py +0 -0
  23. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/models/reaction.py +0 -0
  24. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/models/user.py +0 -0
  25. {max_library-0.2.0 → max_library-0.3.0}/src/max_library/transport/__init__.py +0 -0
  26. {max_library-0.2.0 → max_library-0.3.0}/src/max_library.egg-info/SOURCES.txt +0 -0
  27. {max_library-0.2.0 → max_library-0.3.0}/src/max_library.egg-info/dependency_links.txt +0 -0
  28. {max_library-0.2.0 → max_library-0.3.0}/src/max_library.egg-info/requires.txt +0 -0
  29. {max_library-0.2.0 → max_library-0.3.0}/src/max_library.egg-info/top_level.txt +0 -0
  30. {max_library-0.2.0 → max_library-0.3.0}/tests/test_filters.py +0 -0
  31. {max_library-0.2.0 → max_library-0.3.0}/tests/test_transport.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: max-library
3
- Version: 0.2.0
3
+ Version: 0.3.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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "max-library"
7
- version = "0.2.0"
7
+ version = "0.3.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"
@@ -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.2.0"
30
+ __version__ = "0.3.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,
@@ -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] = []
@@ -275,6 +277,16 @@ class MaxClient:
275
277
  user = User.model_validate(profile).bind_client(self)
276
278
  self.me = user
277
279
  logger.info(f"Authenticated as: {user.display_name} (ID: {user.id})")
280
+
281
+ # Cache initial chats returned in session payload
282
+ raw_chats = resp_payload.get("chats", [])
283
+ for raw_chat in raw_chats:
284
+ try:
285
+ chat_obj = Chat.model_validate(raw_chat).bind_client(self)
286
+ self._chats_cache[str(chat_obj.id)] = chat_obj
287
+ except Exception as e:
288
+ logger.debug(f"Failed to parse initial chat from session: {e}")
289
+
278
290
  return user
279
291
 
280
292
  async def _restore_session_on_reconnect(self) -> None:
@@ -623,9 +635,72 @@ class MaxClient:
623
635
  return True
624
636
 
625
637
  # =========================================================================
626
- # Chat Actions (Opcode 22, 20)
638
+ # Chat Actions (Opcode 48, 19, 22, 20)
627
639
  # =========================================================================
628
640
 
641
+ async def get_chats(self, count: int = 40, force_refresh: bool = False) -> list[Chat]:
642
+ """
643
+ Retrieves list of user chats. Returns cached list from session init unless force_refresh is True.
644
+ """
645
+ if not force_refresh and self._chats_cache:
646
+ return list(self._chats_cache.values())
647
+
648
+ if not self.token:
649
+ raise ValueError("No auth token provided. Authenticate first.")
650
+
651
+ resp = await self.transport.send_request(
652
+ opcode=19,
653
+ payload={
654
+ "interactive": True,
655
+ "token": self.token,
656
+ "chatsSync": 0,
657
+ "contactsSync": 0,
658
+ "presenceSync": 0,
659
+ "draftsSync": 0,
660
+ "chatsCount": count,
661
+ },
662
+ )
663
+ chats_data = resp.get("payload", {}).get("chats", [])
664
+ chats: list[Chat] = []
665
+ for raw in chats_data:
666
+ chat = Chat.model_validate(raw).bind_client(self)
667
+ self._chats_cache[str(chat.id)] = chat
668
+ chats.append(chat)
669
+ return chats
670
+
671
+ async def get_chat(self, chat_id: int | str, force_refresh: bool = False) -> Chat:
672
+ """
673
+ Retrieves detailed chat information by chat ID (Opcode 48).
674
+ Uses internal session cache unless force_refresh is True.
675
+ """
676
+ key = str(chat_id).strip()
677
+ if not force_refresh and key in self._chats_cache:
678
+ return self._chats_cache[key]
679
+
680
+ cid = int(chat_id) if str(chat_id).lstrip("-").isdigit() else chat_id
681
+ resp = await self.transport.send_request(
682
+ opcode=48,
683
+ payload={"chatIds": [cid]},
684
+ )
685
+ chats_data = resp.get("payload", {}).get("chats", [])
686
+ if not chats_data:
687
+ raise ChatNotFoundError(error="chat.not.found", message=f"Chat {chat_id} not found")
688
+
689
+ chat = Chat.model_validate(chats_data[0]).bind_client(self)
690
+
691
+ # For DIALOG chats without explicit title, resolve interlocutor name if possible
692
+ if not chat.title and chat.type == "DIALOG" and isinstance(chat.participants, dict) and self.me:
693
+ other_ids = [uid for uid in chat.participants if str(uid) != str(self.me.id)]
694
+ if other_ids:
695
+ try:
696
+ other_user = await self.get_user(id=other_ids[0])
697
+ chat.title = other_user.display_name
698
+ except Exception as e:
699
+ logger.debug(f"Could not resolve interlocutor for dialog {chat_id}: {e}")
700
+
701
+ self._chats_cache[key] = chat
702
+ return chat
703
+
629
704
  async def pin_chat(self, chat_id: int | str) -> bool:
630
705
  """Pins a chat (Opcode 22)."""
631
706
  await self.transport.send_request(
@@ -52,3 +52,9 @@ class VerifyCodeWrong(AuthError):
52
52
  class UserNotFoundError(MaxAPIError):
53
53
  """Raised when a user is not found by ID or phone number."""
54
54
  pass
55
+
56
+
57
+ class ChatNotFoundError(MaxAPIError):
58
+ """Raised when a chat is not found by ID."""
59
+ pass
60
+
@@ -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
@@ -24,6 +24,7 @@ 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
29
30
 
@@ -285,6 +286,8 @@ class MaxTransport:
285
286
  raise AuthError(error=error, title=title, message=message, payload=payload, raw_response=response)
286
287
  if "user.not.found" in error or error == "contact.not.found":
287
288
  raise UserNotFoundError(error=error, title=title, message=message, payload=payload, raw_response=response)
289
+ if "chat.not.found" in error:
290
+ raise ChatNotFoundError(error=error, title=title, message=message, payload=payload, raw_response=response)
288
291
 
289
292
  raise MaxAPIError(error=error, title=title, message=message, payload=payload, raw_response=response)
290
293
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: max-library
3
- Version: 0.2.0
3
+ Version: 0.3.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
@@ -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"
File without changes
File without changes
File without changes