-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathservice.py
More file actions
445 lines (391 loc) · 13 KB
/
Copy pathservice.py
File metadata and controls
445 lines (391 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
from __future__ import annotations
import time
from collections.abc import Sequence
from typing import TYPE_CHECKING, TypeAlias
from pymax.api.binding import bind_api_model, bind_api_models
from pymax.api.response import (
parse_payload_list,
parse_payload_model,
payload_item,
require_payload_item_model,
require_payload_model,
)
from pymax.api.uploads.payloads import (
AttachFilePayload,
AttachPhotoPayload,
VideoAttachPayload,
)
from pymax.exceptions import UploadError
from pymax.files import File, Photo, Video
from pymax.formatting.markdown import Formatter
from pymax.logging import get_logger
from pymax.protocol import Opcode
from pymax.types.domain import (
FileRequest,
Message,
ReactionInfo,
ReadState,
VideoRequest,
)
from .enums import ItemType, MessagePayloadKey, ReadAction
from .payloads import (
AddReactionPayload,
ChatHistoryPayload,
DeleteMessagePayload,
EditMessagePayload,
ForwardLink,
ForwardMessagePayload,
ForwardMessagePayloadMessage,
GetFilePayload,
GetMessagesPayload,
GetReactionsPayload,
GetVideoPayload,
PinMessagePayload,
ReactionInfoPayload,
ReadMessagesPayload,
RemoveReactionPayload,
ReplyLink,
SendMessagePayload,
SendMessagePayloadMessage,
)
if TYPE_CHECKING:
from pymax.app import App
SendAttachment: TypeAlias = Photo | File | Video
SendAttachments: TypeAlias = Sequence[SendAttachment] | None
logger = get_logger(__name__)
class MessageService:
def __init__(self, app: App) -> None:
self.app = app
self._prev = int(time.time() * 1000)
def _next_cid(self) -> int:
now = int(time.time() * 1000)
e = max(now, self._prev + 1)
self._prev = e
logger.debug("generated message cid=%s", e)
return e
async def _upload_attachments(
self, attachments: SendAttachments
) -> list[AttachPhotoPayload | VideoAttachPayload | AttachFilePayload]:
result: list[AttachPhotoPayload | VideoAttachPayload | AttachFilePayload] = []
if not attachments:
return result
for attachment in attachments:
if isinstance(attachment, Photo):
upload_result = await self.app.api.uploads.upload_photo(attachment)
if not upload_result:
logger.error("Photo uploading failed")
raise UploadError("Photo uploading failed")
result.append(upload_result)
elif isinstance(attachment, Video):
upload_result = await self.app.api.uploads.upload_video(attachment)
if not upload_result:
logger.error("Video uploading failed")
raise UploadError("Video uploading failed")
result.append(upload_result)
elif isinstance(attachment, File):
upload_result = await self.app.api.uploads.upload_file(attachment)
if not upload_result:
logger.error("File uploading failed")
raise UploadError("File uploading failed")
result.append(upload_result)
return result
async def send_message(
self,
chat_id: int,
text: str,
reply_to: int | None = None,
attachments: SendAttachments = None,
*,
notify: bool = True,
) -> Message | None:
logger.info("sending message chat_id=%s text_len=%s", chat_id, len(text))
clean_text, elements = Formatter.format_markdown(text)
frame = SendMessagePayload(
chat_id=chat_id,
message=SendMessagePayloadMessage(
text=clean_text,
cid=self._next_cid(),
elements=elements,
attaches=await self._upload_attachments(attachments),
link=ReplyLink(message_id=reply_to) if reply_to else None,
),
notify=notify,
)
response = await self.app.invoke(Opcode.MSG_SEND, frame.to_payload())
message = bind_api_model(
self.app,
require_payload_model(response, Message),
)
logger.info("message sent chat_id=%s", chat_id)
return message
async def forward_message(
self,
chat_id: int,
message_id: int | str,
source_chat_id: int | None = None,
*,
notify: bool = True,
) -> Message | None:
source_chat_id = chat_id if source_chat_id is None else source_chat_id
logger.info(
"forwarding message source_chat_id=%s chat_id=%s message_id=%s",
source_chat_id,
chat_id,
message_id,
)
frame = ForwardMessagePayload(
chat_id=chat_id,
message=ForwardMessagePayloadMessage(
cid=-self._next_cid(),
link=ForwardLink(
message_id=str(message_id),
chat_id=source_chat_id,
),
),
notify=notify,
)
response = await self.app.invoke(Opcode.MSG_SEND, frame.to_payload())
message = bind_api_model(
self.app,
require_payload_model(response, Message),
)
logger.info("message forwarded source_chat_id=%s chat_id=%s", source_chat_id, chat_id)
return message
async def get_messages(
self,
chat_id: int,
message_ids: list[int],
) -> list[Message]:
frame = GetMessagesPayload(
chat_id=chat_id,
message_ids=message_ids,
)
response = await self.app.invoke(Opcode.MSG_GET, frame.to_payload())
messages = parse_payload_list(response, MessagePayloadKey.MESSAGES, Message)
for message in messages:
if message.chat_id is None:
message.chat_id = chat_id
return bind_api_models(self.app, messages)
async def get_message(
self,
chat_id: int,
message_id: int,
) -> Message | None:
messages = await self.get_messages(chat_id, [message_id])
return messages[0] if messages else None
async def edit_message(
self,
chat_id: int,
message_id: int,
text: str,
attachments: SendAttachments = None,
) -> Message:
clean_text, elements = Formatter.format_markdown(text)
frame = EditMessagePayload(
chat_id=chat_id,
message_id=message_id,
text=clean_text,
elements=elements,
attachments=await self._upload_attachments(attachments),
)
response = await self.app.invoke(Opcode.MSG_EDIT, frame.to_payload())
message = require_payload_item_model(
response,
MessagePayloadKey.MESSAGE,
Message,
)
if message.chat_id is None:
message.chat_id = chat_id
return bind_api_model(self.app, message)
async def fetch_history(
self,
chat_id: int,
forward: int = 0,
backward: int = 40,
backward_time: int = 0,
forward_time: int = 0,
from_: int | None = None,
item_type: ItemType = ItemType.REGULAR,
get_chat: bool = False,
get_messages: bool = True,
interactive: bool = False,
) -> list[Message] | None:
frame = ChatHistoryPayload(
chat_id=chat_id,
forward=forward,
backward=backward,
backward_time=backward_time,
forward_time=forward_time,
from_=from_ or int(time.time() * 1000),
item_type=item_type,
get_chat=get_chat,
get_messages=get_messages,
interactive=interactive,
)
response = await self.app.invoke(
Opcode.CHAT_HISTORY,
payload=frame.to_payload(),
)
messages = bind_api_models(
self.app,
parse_payload_list(response, MessagePayloadKey.MESSAGES, Message),
)
return messages or None
async def delete_message(
self,
chat_id: int,
message_ids: list[int],
for_me: bool,
) -> bool:
logger.info(
"deleting messages chat_id=%s ids=%s for_me=%s",
chat_id,
message_ids,
for_me,
)
frame = DeleteMessagePayload(
chat_id=chat_id,
message_ids=message_ids,
for_me=for_me,
)
await self.app.invoke(Opcode.MSG_DELETE, frame.to_payload())
logger.info("messages deleted chat_id=%s count=%s", chat_id, len(message_ids))
return True
async def pin_message(
self,
chat_id: int,
message_id: int,
notify_pin: bool,
) -> bool:
logger.info(
"pinning message chat_id=%s message_id=%s notify_pin=%s",
chat_id,
message_id,
notify_pin,
)
frame = PinMessagePayload(
chat_id=chat_id,
notify_pin=notify_pin,
pin_message_id=message_id,
)
await self.app.invoke(Opcode.CHAT_UPDATE, frame.to_payload())
logger.info("message pinned chat_id=%s message_id=%s", chat_id, message_id)
return True
async def get_video_by_id(
self,
chat_id: int,
message_id: int | str,
video_id: int,
) -> VideoRequest | None:
logger.info(
"getting video chat_id=%s message_id=%s video_id=%s",
chat_id,
message_id,
video_id,
)
frame = GetVideoPayload(
chat_id=chat_id,
message_id=message_id,
video_id=video_id,
)
response = await self.app.invoke(Opcode.VIDEO_PLAY, frame.to_payload())
return parse_payload_model(response, VideoRequest)
async def get_file_by_id(
self,
chat_id: int,
message_id: int | str,
file_id: int,
) -> FileRequest | None:
logger.info(
"getting file chat_id=%s message_id=%s file_id=%s",
chat_id,
message_id,
file_id,
)
frame = GetFilePayload(
chat_id=chat_id,
message_id=message_id,
file_id=file_id,
)
response = await self.app.invoke(Opcode.FILE_DOWNLOAD, frame.to_payload())
return parse_payload_model(response, FileRequest)
async def add_reaction(
self,
chat_id: int,
message_id: str,
reaction: str,
) -> ReactionInfo | None:
logger.info(
"adding reaction chat_id=%s message_id=%s reaction=%s",
chat_id,
message_id,
reaction,
)
frame = AddReactionPayload(
chat_id=chat_id,
message_id=message_id,
reaction=ReactionInfoPayload(id=reaction),
)
response = await self.app.invoke(Opcode.MSG_REACTION, frame.to_payload())
reaction_info = payload_item(response, MessagePayloadKey.REACTION_INFO)
if reaction_info:
return ReactionInfo.model_validate(reaction_info)
return None
async def get_reactions(
self,
chat_id: int,
message_ids: list[str],
) -> dict[str, ReactionInfo] | None:
logger.info(
"getting reactions chat_id=%s message_ids=%s",
chat_id,
message_ids,
)
frame = GetReactionsPayload(chat_id=chat_id, message_ids=message_ids)
response = await self.app.invoke(
Opcode.MSG_GET_REACTIONS,
frame.to_payload(),
)
messages_reactions = payload_item(
response,
MessagePayloadKey.MESSAGES_REACTIONS,
)
if messages_reactions is None:
return None
return {
message_id: ReactionInfo.model_validate(reaction_data)
for message_id, reaction_data in messages_reactions.items()
}
async def remove_reaction(
self,
chat_id: int,
message_id: str,
) -> ReactionInfo | None:
logger.info(
"removing reaction chat_id=%s message_id=%s",
chat_id,
message_id,
)
frame = RemoveReactionPayload(chat_id=chat_id, message_id=message_id)
response = await self.app.invoke(
Opcode.MSG_CANCEL_REACTION,
frame.to_payload(),
)
reaction_info = payload_item(response, MessagePayloadKey.REACTION_INFO)
if reaction_info:
return ReactionInfo.model_validate(reaction_info)
return None
async def read_message(self, message_id: int | str, chat_id: int) -> ReadState:
logger.info(
"marking message as read chat_id=%s message_id=%s",
chat_id,
message_id,
)
frame = ReadMessagesPayload(
type=ReadAction.READ_MESSAGE,
chat_id=chat_id,
message_id=message_id,
mark=int(time.time() * 1000),
)
response = await self.app.invoke(Opcode.CHAT_MARK, frame.to_payload())
return require_payload_model(response, ReadState)