maxapi-python 0.1.0__py3-none-any.whl → 0.1.2__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.
- maxapi_python-0.1.2.dist-info/METADATA +163 -0
- maxapi_python-0.1.2.dist-info/RECORD +25 -0
- {maxapi_python-0.1.0.dist-info → maxapi_python-0.1.2.dist-info}/WHEEL +1 -2
- pymax/core.py +37 -481
- pymax/crud.py +1 -1
- pymax/files.py +85 -0
- pymax/filters.py +38 -0
- pymax/interfaces.py +67 -0
- pymax/mixins/__init__.py +18 -0
- pymax/mixins/auth.py +81 -0
- pymax/mixins/channel.py +25 -0
- pymax/mixins/group.py +220 -0
- pymax/mixins/handler.py +60 -0
- pymax/mixins/message.py +293 -0
- pymax/mixins/self.py +38 -0
- pymax/mixins/user.py +82 -0
- pymax/mixins/websocket.py +242 -0
- pymax/payloads.py +175 -0
- pymax/static.py +143 -19
- pymax/types.py +134 -29
- pymax/utils.py +38 -0
- maxapi_python-0.1.0.dist-info/METADATA +0 -110
- maxapi_python-0.1.0.dist-info/RECORD +0 -12
- maxapi_python-0.1.0.dist-info/top_level.txt +0 -1
- {maxapi_python-0.1.0.dist-info → maxapi_python-0.1.2.dist-info}/licenses/LICENSE +0 -0
pymax/mixins/message.py
ADDED
@@ -0,0 +1,293 @@
|
|
1
|
+
import time
|
2
|
+
|
3
|
+
import aiohttp
|
4
|
+
from aiohttp import ClientSession
|
5
|
+
|
6
|
+
from pymax.files import File, Photo, Video
|
7
|
+
from pymax.interfaces import ClientProtocol
|
8
|
+
from pymax.payloads import (
|
9
|
+
AttachPhotoPayload,
|
10
|
+
DeleteMessagePayload,
|
11
|
+
EditMessagePayload,
|
12
|
+
FetchHistoryPayload,
|
13
|
+
PinMessagePayload,
|
14
|
+
ReplyLink,
|
15
|
+
SendMessagePayload,
|
16
|
+
SendMessagePayloadMessage,
|
17
|
+
UploadPhotoPayload,
|
18
|
+
)
|
19
|
+
from pymax.static import AttachType, Opcode
|
20
|
+
from pymax.types import Attach, Message
|
21
|
+
|
22
|
+
|
23
|
+
class MessageMixin(ClientProtocol):
|
24
|
+
async def _upload_photo(self, photo: Photo) -> None | Attach:
|
25
|
+
try:
|
26
|
+
self.logger.info("Uploading photo")
|
27
|
+
payload = UploadPhotoPayload().model_dump(by_alias=True)
|
28
|
+
|
29
|
+
data = await self._send_and_wait(
|
30
|
+
opcode=Opcode.PHOTO_UPLOAD,
|
31
|
+
payload=payload,
|
32
|
+
)
|
33
|
+
if error := data.get("payload", {}).get("error"):
|
34
|
+
self.logger.error("Upload photo error: %s", error)
|
35
|
+
return None
|
36
|
+
|
37
|
+
url = data.get("payload", {}).get("url")
|
38
|
+
if not url:
|
39
|
+
self.logger.error("No upload URL received")
|
40
|
+
return None
|
41
|
+
|
42
|
+
photo_data = photo.validate_photo()
|
43
|
+
if not photo_data:
|
44
|
+
self.logger.error("Photo validation failed")
|
45
|
+
return None
|
46
|
+
|
47
|
+
form = aiohttp.FormData()
|
48
|
+
form.add_field(
|
49
|
+
name="file",
|
50
|
+
value=await photo.read(),
|
51
|
+
filename=f"image.{photo_data[0]}",
|
52
|
+
content_type=photo_data[1],
|
53
|
+
)
|
54
|
+
|
55
|
+
async with (
|
56
|
+
ClientSession() as session,
|
57
|
+
session.post(
|
58
|
+
url=url,
|
59
|
+
data=form,
|
60
|
+
) as response,
|
61
|
+
):
|
62
|
+
if response.status != 200:
|
63
|
+
self.logger.error(f"Upload failed with status {response.status}")
|
64
|
+
return None
|
65
|
+
|
66
|
+
result = await response.json()
|
67
|
+
|
68
|
+
if not result.get("photos"):
|
69
|
+
self.logger.error("No photos in response")
|
70
|
+
return None
|
71
|
+
|
72
|
+
photo_data = next(iter(result["photos"].values()), None)
|
73
|
+
if not photo_data or "token" not in photo_data:
|
74
|
+
self.logger.error("No token in response")
|
75
|
+
return None
|
76
|
+
|
77
|
+
return Attach(
|
78
|
+
_type=AttachType.PHOTO,
|
79
|
+
photo_token=photo_data["token"],
|
80
|
+
)
|
81
|
+
|
82
|
+
except Exception as e:
|
83
|
+
self.logger.exception("Upload photo failed: %s", str(e))
|
84
|
+
return None
|
85
|
+
|
86
|
+
async def send_message(
|
87
|
+
self,
|
88
|
+
text: str,
|
89
|
+
chat_id: int,
|
90
|
+
notify: bool,
|
91
|
+
photo: Photo | None = None,
|
92
|
+
photos: list[Photo] | None = None,
|
93
|
+
reply_to: int | None = None,
|
94
|
+
) -> Message | None:
|
95
|
+
"""
|
96
|
+
Отправляет сообщение в чат.
|
97
|
+
"""
|
98
|
+
try:
|
99
|
+
self.logger.info("Sending message to chat_id=%s notify=%s", chat_id, notify)
|
100
|
+
if photos and photo:
|
101
|
+
self.logger.warning("Both photo and photos provided; using photos")
|
102
|
+
photo = None
|
103
|
+
attaches = []
|
104
|
+
if photo:
|
105
|
+
self.logger.info("Uploading photo for message")
|
106
|
+
attach = await self._upload_photo(photo)
|
107
|
+
if not attach or not attach.photo_token:
|
108
|
+
self.logger.error("Photo upload failed, message not sent")
|
109
|
+
return None
|
110
|
+
attaches = [
|
111
|
+
AttachPhotoPayload(photo_token=attach.photo_token).model_dump(
|
112
|
+
by_alias=True
|
113
|
+
)
|
114
|
+
]
|
115
|
+
elif photos:
|
116
|
+
self.logger.info("Uploading multiple photos for message")
|
117
|
+
for p in photos:
|
118
|
+
attach = await self._upload_photo(p)
|
119
|
+
if attach and attach.photo_token:
|
120
|
+
attaches.append(
|
121
|
+
AttachPhotoPayload(
|
122
|
+
photo_token=attach.photo_token
|
123
|
+
).model_dump(by_alias=True)
|
124
|
+
)
|
125
|
+
if not attaches:
|
126
|
+
self.logger.error("All photo uploads failed, message not sent")
|
127
|
+
return None
|
128
|
+
|
129
|
+
payload = SendMessagePayload(
|
130
|
+
chat_id=chat_id,
|
131
|
+
message=SendMessagePayloadMessage(
|
132
|
+
text=text,
|
133
|
+
cid=int(time.time() * 1000),
|
134
|
+
elements=[],
|
135
|
+
attaches=attaches,
|
136
|
+
link=ReplyLink(message_id=str(reply_to)) if reply_to else None,
|
137
|
+
),
|
138
|
+
notify=notify,
|
139
|
+
).model_dump(by_alias=True)
|
140
|
+
|
141
|
+
data = await self._send_and_wait(opcode=Opcode.MSG_SEND, payload=payload)
|
142
|
+
if error := data.get("payload", {}).get("error"):
|
143
|
+
self.logger.error("Send message error: %s", error)
|
144
|
+
print(data)
|
145
|
+
return None
|
146
|
+
msg = (
|
147
|
+
Message.from_dict(data["payload"]["message"])
|
148
|
+
if data.get("payload")
|
149
|
+
else None
|
150
|
+
)
|
151
|
+
self.logger.debug("send_message result: %r", msg)
|
152
|
+
return msg
|
153
|
+
except Exception:
|
154
|
+
self.logger.exception("Send message failed")
|
155
|
+
return None
|
156
|
+
|
157
|
+
async def edit_message(
|
158
|
+
self, chat_id: int, message_id: int, text: str
|
159
|
+
) -> Message | None:
|
160
|
+
"""
|
161
|
+
Редактирует сообщение.
|
162
|
+
"""
|
163
|
+
try:
|
164
|
+
self.logger.info(
|
165
|
+
"Editing message chat_id=%s message_id=%s", chat_id, message_id
|
166
|
+
)
|
167
|
+
payload = EditMessagePayload(
|
168
|
+
chat_id=chat_id,
|
169
|
+
message_id=message_id,
|
170
|
+
text=text,
|
171
|
+
elements=[],
|
172
|
+
attaches=[],
|
173
|
+
).model_dump(by_alias=True)
|
174
|
+
data = await self._send_and_wait(opcode=Opcode.MSG_EDIT, payload=payload)
|
175
|
+
if error := data.get("payload", {}).get("error"):
|
176
|
+
self.logger.error("Edit message error: %s", error)
|
177
|
+
msg = (
|
178
|
+
Message.from_dict(data["payload"]["message"])
|
179
|
+
if data.get("payload")
|
180
|
+
else None
|
181
|
+
)
|
182
|
+
self.logger.debug("edit_message result: %r", msg)
|
183
|
+
return msg
|
184
|
+
except Exception:
|
185
|
+
self.logger.exception("Edit message failed")
|
186
|
+
return None
|
187
|
+
|
188
|
+
async def delete_message(
|
189
|
+
self, chat_id: int, message_ids: list[int], for_me: bool
|
190
|
+
) -> bool:
|
191
|
+
"""
|
192
|
+
Удаляет сообщения.
|
193
|
+
"""
|
194
|
+
try:
|
195
|
+
self.logger.info(
|
196
|
+
"Deleting messages chat_id=%s ids=%s for_me=%s",
|
197
|
+
chat_id,
|
198
|
+
message_ids,
|
199
|
+
for_me,
|
200
|
+
)
|
201
|
+
|
202
|
+
payload = DeleteMessagePayload(
|
203
|
+
chat_id=chat_id, message_ids=message_ids, for_me=for_me
|
204
|
+
).model_dump(by_alias=True)
|
205
|
+
|
206
|
+
data = await self._send_and_wait(opcode=Opcode.MSG_DELETE, payload=payload)
|
207
|
+
if error := data.get("payload", {}).get("error"):
|
208
|
+
self.logger.error("Delete message error: %s", error)
|
209
|
+
return False
|
210
|
+
self.logger.debug("delete_message success")
|
211
|
+
return True
|
212
|
+
except Exception:
|
213
|
+
self.logger.exception("Delete message failed")
|
214
|
+
return False
|
215
|
+
|
216
|
+
async def pin_message(
|
217
|
+
self, chat_id: int, message_id: int, notify_pin: bool
|
218
|
+
) -> bool:
|
219
|
+
"""
|
220
|
+
Закрепляет сообщение.
|
221
|
+
|
222
|
+
Args:
|
223
|
+
chat_id (int): ID чата
|
224
|
+
message_id (int): ID сообщения
|
225
|
+
notify_pin (bool): Оповещать о закреплении
|
226
|
+
|
227
|
+
Returns:
|
228
|
+
bool: True, если сообщение закреплено
|
229
|
+
"""
|
230
|
+
try:
|
231
|
+
payload = PinMessagePayload(
|
232
|
+
chat_id=chat_id,
|
233
|
+
notify_pin=notify_pin,
|
234
|
+
pin_message_id=message_id,
|
235
|
+
).model_dump(by_alias=True)
|
236
|
+
|
237
|
+
data = await self._send_and_wait(opcode=Opcode.CHAT_UPDATE, payload=payload)
|
238
|
+
if error := data.get("payload", {}).get("error"):
|
239
|
+
self.logger.error("Pin message error: %s", error)
|
240
|
+
return False
|
241
|
+
self.logger.debug("pin_message success")
|
242
|
+
return True
|
243
|
+
except Exception:
|
244
|
+
self.logger.exception("Pin message failed")
|
245
|
+
return False
|
246
|
+
|
247
|
+
async def fetch_history(
|
248
|
+
self,
|
249
|
+
chat_id: int,
|
250
|
+
from_time: int | None = None,
|
251
|
+
forward: int = 0,
|
252
|
+
backward: int = 200,
|
253
|
+
) -> list[Message] | None:
|
254
|
+
"""
|
255
|
+
Получает историю сообщений чата.
|
256
|
+
"""
|
257
|
+
if from_time is None:
|
258
|
+
from_time = int(time.time() * 1000)
|
259
|
+
|
260
|
+
try:
|
261
|
+
self.logger.info(
|
262
|
+
"Fetching history chat_id=%s from=%s forward=%s backward=%s",
|
263
|
+
chat_id,
|
264
|
+
from_time,
|
265
|
+
forward,
|
266
|
+
backward,
|
267
|
+
)
|
268
|
+
|
269
|
+
payload = FetchHistoryPayload(
|
270
|
+
chat_id=chat_id,
|
271
|
+
from_time=from_time, # pyright: ignore[reportCallIssue] FIXME: Pydantic Field alias
|
272
|
+
forward=forward,
|
273
|
+
backward=backward,
|
274
|
+
).model_dump(by_alias=True)
|
275
|
+
|
276
|
+
self.logger.debug("Payload dict keys: %s", list(payload.keys()))
|
277
|
+
|
278
|
+
data = await self._send_and_wait(
|
279
|
+
opcode=Opcode.CHAT_HISTORY, payload=payload, timeout=10
|
280
|
+
)
|
281
|
+
|
282
|
+
if error := data.get("payload", {}).get("error"):
|
283
|
+
self.logger.error("Fetch history error: %s", error)
|
284
|
+
return None
|
285
|
+
|
286
|
+
messages = [
|
287
|
+
Message.from_dict(msg) for msg in data["payload"].get("messages", [])
|
288
|
+
]
|
289
|
+
self.logger.debug("History fetched: %d messages", len(messages))
|
290
|
+
return messages
|
291
|
+
except Exception:
|
292
|
+
self.logger.exception("Fetch history failed")
|
293
|
+
return None
|
pymax/mixins/self.py
ADDED
@@ -0,0 +1,38 @@
|
|
1
|
+
from pymax.interfaces import ClientProtocol
|
2
|
+
from pymax.payloads import ChangeProfilePayload
|
3
|
+
from pymax.static import Opcode
|
4
|
+
|
5
|
+
|
6
|
+
class SelfMixin(ClientProtocol):
|
7
|
+
async def change_profile(
|
8
|
+
self,
|
9
|
+
first_name: str,
|
10
|
+
last_name: str | None = None,
|
11
|
+
description: str | None = None,
|
12
|
+
) -> bool:
|
13
|
+
"""
|
14
|
+
Изменяет профиль
|
15
|
+
|
16
|
+
Args:
|
17
|
+
first_name (str): Имя.
|
18
|
+
last_name (str | None, optional): Фамилия. Defaults to None.
|
19
|
+
description (str | None, optional): Описание. Defaults to None.
|
20
|
+
|
21
|
+
Returns:
|
22
|
+
bool: True, если профиль изменен
|
23
|
+
"""
|
24
|
+
|
25
|
+
payload = ChangeProfilePayload(
|
26
|
+
first_name=first_name,
|
27
|
+
last_name=last_name,
|
28
|
+
description=description,
|
29
|
+
).model_dump(
|
30
|
+
by_alias=True,
|
31
|
+
exclude_none=True,
|
32
|
+
)
|
33
|
+
|
34
|
+
data = await self._send_and_wait(opcode=Opcode.PROFILE, payload=payload)
|
35
|
+
if error := data.get("payload", {}).get("error"):
|
36
|
+
self.logger.error("Change profile error: %s", error)
|
37
|
+
return False
|
38
|
+
return True
|
pymax/mixins/user.py
ADDED
@@ -0,0 +1,82 @@
|
|
1
|
+
from pymax.interfaces import ClientProtocol
|
2
|
+
from pymax.payloads import FetchContactsPayload
|
3
|
+
from pymax.static import Opcode
|
4
|
+
from pymax.types import User
|
5
|
+
|
6
|
+
|
7
|
+
class UserMixin(ClientProtocol):
|
8
|
+
def get_cached_user(self, user_id: int) -> User | None:
|
9
|
+
"""
|
10
|
+
Получает юзера из кеша по его ID
|
11
|
+
|
12
|
+
Args:
|
13
|
+
user_id (int): ID пользователя.
|
14
|
+
|
15
|
+
Returns:
|
16
|
+
User | None: Объект User или None при ошибке.
|
17
|
+
"""
|
18
|
+
user = self._users.get(user_id)
|
19
|
+
self.logger.debug("get_cached_user id=%s hit=%s", user_id, bool(user))
|
20
|
+
return user
|
21
|
+
|
22
|
+
async def get_users(self, user_ids: list[int]) -> list[User]:
|
23
|
+
"""
|
24
|
+
Получает информацию о пользователях по их ID (с кешем).
|
25
|
+
"""
|
26
|
+
self.logger.debug("get_users ids=%s", user_ids)
|
27
|
+
cached = {uid: self._users[uid] for uid in user_ids if uid in self._users}
|
28
|
+
missing_ids = [uid for uid in user_ids if uid not in self._users]
|
29
|
+
|
30
|
+
if missing_ids:
|
31
|
+
self.logger.debug("Fetching missing users: %s", missing_ids)
|
32
|
+
fetched_users = await self.fetch_users(missing_ids)
|
33
|
+
if fetched_users:
|
34
|
+
for user in fetched_users:
|
35
|
+
self._users[user.id] = user
|
36
|
+
cached[user.id] = user
|
37
|
+
|
38
|
+
ordered = [cached[uid] for uid in user_ids if uid in cached]
|
39
|
+
self.logger.debug("get_users result_count=%d", len(ordered))
|
40
|
+
return ordered
|
41
|
+
|
42
|
+
async def get_user(self, user_id: int) -> User | None:
|
43
|
+
"""
|
44
|
+
Получает информацию о пользователе по его ID (с кешем).
|
45
|
+
"""
|
46
|
+
self.logger.debug("get_user id=%s", user_id)
|
47
|
+
if user_id in self._users:
|
48
|
+
return self._users[user_id]
|
49
|
+
|
50
|
+
users = await self.fetch_users([user_id])
|
51
|
+
if users:
|
52
|
+
self._users[user_id] = users[0]
|
53
|
+
return users[0]
|
54
|
+
return None
|
55
|
+
|
56
|
+
async def fetch_users(self, user_ids: list[int]) -> None | list[User]:
|
57
|
+
"""
|
58
|
+
Получает информацию о пользователях по их ID.
|
59
|
+
"""
|
60
|
+
try:
|
61
|
+
self.logger.info("Fetching users count=%d", len(user_ids))
|
62
|
+
|
63
|
+
payload = FetchContactsPayload(contact_ids=user_ids).model_dump(
|
64
|
+
by_alias=True
|
65
|
+
)
|
66
|
+
|
67
|
+
data = await self._send_and_wait(
|
68
|
+
opcode=Opcode.CONTACT_INFO, payload=payload
|
69
|
+
)
|
70
|
+
if error := data.get("payload", {}).get("error"):
|
71
|
+
self.logger.error("Fetch users error: %s", error)
|
72
|
+
return None
|
73
|
+
|
74
|
+
users = [User.from_dict(u) for u in data["payload"].get("contacts", [])]
|
75
|
+
for user in users:
|
76
|
+
self._users[user.id] = user
|
77
|
+
|
78
|
+
self.logger.debug("Fetched users: %d", len(users))
|
79
|
+
return users
|
80
|
+
except Exception:
|
81
|
+
self.logger.exception("Fetch users failed")
|
82
|
+
return []
|
@@ -0,0 +1,242 @@
|
|
1
|
+
import asyncio
|
2
|
+
import json
|
3
|
+
from typing import Any, override
|
4
|
+
|
5
|
+
import websockets
|
6
|
+
|
7
|
+
from pymax.exceptions import WebSocketNotConnectedError
|
8
|
+
from pymax.interfaces import ClientProtocol
|
9
|
+
from pymax.payloads import BaseWebSocketMessage, SyncPayload
|
10
|
+
from pymax.static import ChatType, Constants, Opcode
|
11
|
+
from pymax.types import Channel, Chat, Dialog, Me, Message
|
12
|
+
|
13
|
+
|
14
|
+
class WebSocketMixin(ClientProtocol):
|
15
|
+
@property
|
16
|
+
def ws(self) -> websockets.ClientConnection:
|
17
|
+
if self._ws is None or not self.is_connected:
|
18
|
+
self.logger.critical("WebSocket not connected when access attempted")
|
19
|
+
raise WebSocketNotConnectedError
|
20
|
+
return self._ws
|
21
|
+
|
22
|
+
def _make_message(
|
23
|
+
self, opcode: int, payload: dict[str, Any], cmd: int = 0
|
24
|
+
) -> dict[str, Any]:
|
25
|
+
self._seq += 1
|
26
|
+
|
27
|
+
msg = BaseWebSocketMessage(
|
28
|
+
ver=11,
|
29
|
+
cmd=cmd,
|
30
|
+
seq=self._seq,
|
31
|
+
opcode=opcode,
|
32
|
+
payload=payload,
|
33
|
+
).model_dump(by_alias=True)
|
34
|
+
|
35
|
+
self.logger.debug(
|
36
|
+
"make_message opcode=%s cmd=%s seq=%s", opcode, cmd, self._seq
|
37
|
+
)
|
38
|
+
return msg
|
39
|
+
|
40
|
+
async def _send_interactive_ping(self) -> None:
|
41
|
+
while self.is_connected:
|
42
|
+
try:
|
43
|
+
await self._send_and_wait(
|
44
|
+
opcode=1,
|
45
|
+
payload={"interactive": True},
|
46
|
+
cmd=0,
|
47
|
+
)
|
48
|
+
self.logger.debug("Interactive ping sent successfully")
|
49
|
+
except Exception:
|
50
|
+
self.logger.warning("Interactive ping failed", exc_info=True)
|
51
|
+
await asyncio.sleep(30)
|
52
|
+
|
53
|
+
async def _connect(self, user_agent: dict[str, Any]) -> dict[str, Any]:
|
54
|
+
try:
|
55
|
+
self.logger.info("Connecting to WebSocket %s", self.uri)
|
56
|
+
self._ws = await websockets.connect(self.uri, origin="https://web.max.ru")
|
57
|
+
self.is_connected = True
|
58
|
+
self._incoming = asyncio.Queue()
|
59
|
+
self._pending = {}
|
60
|
+
self._recv_task = asyncio.create_task(self._recv_loop())
|
61
|
+
self.logger.info("WebSocket connected, starting handshake")
|
62
|
+
return await self._handshake(user_agent)
|
63
|
+
except Exception as e:
|
64
|
+
self.logger.error("Failed to connect: %s", e, exc_info=True)
|
65
|
+
raise ConnectionError(f"Failed to connect: {e}")
|
66
|
+
|
67
|
+
async def _handshake(self, user_agent: dict[str, Any]) -> dict[str, Any]:
|
68
|
+
try:
|
69
|
+
self.logger.debug(
|
70
|
+
"Sending handshake with user_agent keys=%s", list(user_agent.keys())
|
71
|
+
)
|
72
|
+
resp = await self._send_and_wait(
|
73
|
+
opcode=Opcode.SESSION_INIT,
|
74
|
+
payload={"deviceId": str(self._device_id), "userAgent": user_agent},
|
75
|
+
)
|
76
|
+
self.logger.info("Handshake completed")
|
77
|
+
return resp
|
78
|
+
except Exception as e:
|
79
|
+
self.logger.error("Handshake failed: %s", e, exc_info=True)
|
80
|
+
raise ConnectionError(f"Handshake failed: {e}")
|
81
|
+
|
82
|
+
async def _recv_loop(self) -> None:
|
83
|
+
if self._ws is None:
|
84
|
+
self.logger.warning("Recv loop started without websocket instance")
|
85
|
+
return
|
86
|
+
|
87
|
+
self.logger.debug("Receive loop started")
|
88
|
+
while True:
|
89
|
+
try:
|
90
|
+
raw = await self._ws.recv()
|
91
|
+
try:
|
92
|
+
data = json.loads(raw)
|
93
|
+
except Exception:
|
94
|
+
self.logger.warning("JSON parse error", exc_info=True)
|
95
|
+
continue
|
96
|
+
|
97
|
+
seq = data.get("seq")
|
98
|
+
fut = self._pending.get(seq) if isinstance(seq, int) else None
|
99
|
+
|
100
|
+
if fut and not fut.done():
|
101
|
+
fut.set_result(data)
|
102
|
+
self.logger.debug("Matched response for pending seq=%s", seq)
|
103
|
+
else:
|
104
|
+
if self._incoming is not None:
|
105
|
+
try:
|
106
|
+
self._incoming.put_nowait(data)
|
107
|
+
except asyncio.QueueFull:
|
108
|
+
self.logger.warning(
|
109
|
+
"Incoming queue full; dropping message seq=%s",
|
110
|
+
data.get("seq"),
|
111
|
+
)
|
112
|
+
|
113
|
+
if (
|
114
|
+
data.get("opcode") == Opcode.NOTIF_MESSAGE
|
115
|
+
and self._on_message_handlers
|
116
|
+
):
|
117
|
+
try:
|
118
|
+
for handler, filter in self._on_message_handlers:
|
119
|
+
payload = data.get("payload", {})
|
120
|
+
msg = Message.from_dict(payload.get("message"))
|
121
|
+
if msg:
|
122
|
+
if msg.status:
|
123
|
+
continue # TODO: заглушка! сделать отдельный хендлер
|
124
|
+
if filter:
|
125
|
+
if filter.match(msg):
|
126
|
+
result = handler(msg)
|
127
|
+
else:
|
128
|
+
continue
|
129
|
+
else:
|
130
|
+
result = handler(msg)
|
131
|
+
if asyncio.iscoroutine(result):
|
132
|
+
task = asyncio.create_task(result)
|
133
|
+
self._background_tasks.add(task)
|
134
|
+
task.add_done_callback(
|
135
|
+
lambda t: self._background_tasks.discard(t)
|
136
|
+
or self._log_task_exception(t)
|
137
|
+
)
|
138
|
+
except Exception:
|
139
|
+
self.logger.exception("Error in on_message_handler")
|
140
|
+
|
141
|
+
except websockets.exceptions.ConnectionClosed:
|
142
|
+
self.logger.info("WebSocket connection closed; exiting recv loop")
|
143
|
+
break
|
144
|
+
except Exception:
|
145
|
+
self.logger.exception("Error in recv_loop; backing off briefly")
|
146
|
+
await asyncio.sleep(0.5)
|
147
|
+
|
148
|
+
def _log_task_exception(self, task: asyncio.Task[Any]) -> None:
|
149
|
+
try:
|
150
|
+
exc = task.exception()
|
151
|
+
if exc:
|
152
|
+
self.logger.exception("Background task exception: %s", exc)
|
153
|
+
except Exception:
|
154
|
+
pass
|
155
|
+
|
156
|
+
@override
|
157
|
+
async def _send_and_wait(
|
158
|
+
self,
|
159
|
+
opcode: int,
|
160
|
+
payload: dict[str, Any],
|
161
|
+
cmd: int = 0,
|
162
|
+
timeout: float = Constants.DEFAULT_TIMEOUT.value,
|
163
|
+
) -> dict[str, Any]:
|
164
|
+
ws = self.ws
|
165
|
+
|
166
|
+
msg = self._make_message(opcode, payload, cmd)
|
167
|
+
loop = asyncio.get_running_loop()
|
168
|
+
fut: asyncio.Future[dict[str, Any]] = loop.create_future()
|
169
|
+
self._pending[msg["seq"]] = fut
|
170
|
+
|
171
|
+
try:
|
172
|
+
self.logger.debug(
|
173
|
+
"Sending frame opcode=%s cmd=%s seq=%s", opcode, cmd, msg["seq"]
|
174
|
+
)
|
175
|
+
await ws.send(json.dumps(msg))
|
176
|
+
data = await asyncio.wait_for(fut, timeout=timeout)
|
177
|
+
self.logger.debug(
|
178
|
+
"Received frame for seq=%s opcode=%s",
|
179
|
+
data.get("seq"),
|
180
|
+
data.get("opcode"),
|
181
|
+
)
|
182
|
+
return data
|
183
|
+
except Exception:
|
184
|
+
self.logger.exception(
|
185
|
+
"Send and wait failed (opcode=%s, seq=%s)", opcode, msg["seq"]
|
186
|
+
)
|
187
|
+
raise RuntimeError("Send and wait failed")
|
188
|
+
finally:
|
189
|
+
self._pending.pop(msg["seq"], None)
|
190
|
+
|
191
|
+
async def _sync(self) -> None:
|
192
|
+
try:
|
193
|
+
self.logger.info("Starting initial sync")
|
194
|
+
|
195
|
+
payload = SyncPayload(
|
196
|
+
interactive=True,
|
197
|
+
token=self._token,
|
198
|
+
chats_sync=0,
|
199
|
+
contacts_sync=0,
|
200
|
+
presence_sync=0,
|
201
|
+
drafts_sync=0,
|
202
|
+
chats_count=40,
|
203
|
+
).model_dump(by_alias=True)
|
204
|
+
|
205
|
+
data = await self._send_and_wait(opcode=19, payload=payload)
|
206
|
+
raw_payload = data.get("payload", {})
|
207
|
+
|
208
|
+
if error := raw_payload.get("error"):
|
209
|
+
self.logger.error("Sync error: %s", error)
|
210
|
+
return
|
211
|
+
|
212
|
+
for raw_chat in raw_payload.get("chats", []):
|
213
|
+
try:
|
214
|
+
if raw_chat.get("type") == ChatType.DIALOG.value:
|
215
|
+
self.dialogs.append(Dialog.from_dict(raw_chat))
|
216
|
+
elif raw_chat.get("type") == ChatType.CHAT.value:
|
217
|
+
self.chats.append(Chat.from_dict(raw_chat))
|
218
|
+
elif raw_chat.get("type") == ChatType.CHANNEL.value:
|
219
|
+
self.channels.append(Channel.from_dict(raw_chat))
|
220
|
+
except Exception:
|
221
|
+
self.logger.exception("Error parsing chat entry")
|
222
|
+
|
223
|
+
if raw_payload.get("profile", {}).get("contact"):
|
224
|
+
self.me = Me.from_dict(
|
225
|
+
raw_payload.get("profile", {}).get("contact", {})
|
226
|
+
)
|
227
|
+
|
228
|
+
self.logger.info(
|
229
|
+
"Sync completed: dialogs=%d chats=%d channels=%d",
|
230
|
+
len(self.dialogs),
|
231
|
+
len(self.chats),
|
232
|
+
len(self.channels),
|
233
|
+
)
|
234
|
+
except Exception:
|
235
|
+
self.logger.exception("Sync failed")
|
236
|
+
|
237
|
+
@override
|
238
|
+
async def _get_chat(self, chat_id: int) -> Chat | None:
|
239
|
+
for chat in self.chats:
|
240
|
+
if chat.id == chat_id:
|
241
|
+
return chat
|
242
|
+
return None
|