-
Notifications
You must be signed in to change notification settings - Fork 133
/
ApiExtensions.php
478 lines (425 loc) · 16.1 KB
/
ApiExtensions.php
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
<?php
namespace TelegramApiServer\MadelineProtoExtensions;
use Amp\ByteStream\ReadableBuffer;
use Amp\ByteStream\WritableResourceStream;
use Amp\Http\Server\FormParser\StreamedField;
use Amp\Http\Server\Request;
use Amp\Http\Server\Response;
use danog\MadelineProto;
use danog\MadelineProto\ParseMode;
use danog\MadelineProto\StrTools;
use InvalidArgumentException;
use TelegramApiServer\Client;
use TelegramApiServer\EventObservers\EventHandler;
use TelegramApiServer\Exceptions\NoMediaException;
use function Amp\delay;
final class ApiExtensions
{
private MadelineProto\Api $madelineProto;
private Request $request;
private ?StreamedField $file;
public function __construct(MadelineProto\Api $madelineProto, Request $request, ?StreamedField $file)
{
$this->madelineProto = $madelineProto;
$this->request = $request;
$this->file = $file;
}
public function getHistoryHtml(array $data): array
{
$response = $this->madelineProto->messages->getHistory(...$data);
if (!empty($response['messages'])) {
foreach ($response['messages'] as &$message) {
$message['message'] = $this->formatMessage($message['message'] ?? null, $message['entities'] ?? []);
}
unset($message);
}
return $response;
}
/**
* Проверяет есть ли подходящие медиа у сообщения.
*
*
*/
private static function hasMedia(array $message = [], bool $allowWebPage = false): bool
{
$mediaType = $message['media']['_'] ?? null;
if ($mediaType === null) {
return false;
}
if (
$mediaType === 'messageMediaWebPage' &&
($allowWebPage === false || empty($message['media']['webpage']['photo']))
) {
return false;
}
return true;
}
public function formatMessage(?string $message = null, array $entities = []): ?string
{
if ($message === null) {
return null;
}
$html = [
'messageEntityItalic' => '<i>%s</i>',
'messageEntityBold' => '<strong>%s</strong>',
'messageEntityCode' => '<code>%s</code>',
'messageEntityPre' => '<pre>%s</pre>',
'messageEntityStrike' => '<strike>%s</strike>',
'messageEntityUnderline' => '<u>%s</u>',
'messageEntityBlockquote' => '<blockquote>%s</blockquote>',
'messageEntityTextUrl' => '<a href="%s" target="_blank" rel="nofollow">%s</a>',
'messageEntityMention' => '<a href="tg://resolve?domain=%s" rel="nofollow">%s</a>',
'messageEntityUrl' => '<a href="%s" target="_blank" rel="nofollow">%s</a>',
];
foreach ($entities as $key => &$entity) {
if (isset($html[$entity['_']])) {
$text = StrTools::mbSubstr($message, $entity['offset'], $entity['length']);
$template = $html[$entity['_']];
if (\in_array($entity['_'], ['messageEntityTextUrl', 'messageEntityMention', 'messageEntityUrl'])) {
$textFormated = \sprintf($template, \strip_tags($entity['url'] ?? $text), $text);
} else {
$textFormated = \sprintf($template, $text);
}
$message = self::substringReplace($message, $textFormated, $entity['offset'], $entity['length']);
//Увеличим оффсеты всех следующих entity
foreach ($entities as $nextKey => &$nextEntity) {
if ($nextKey <= $key) {
continue;
}
if ($nextEntity['offset'] < ($entity['offset'] + $entity['length'])) {
$nextEntity['offset'] += StrTools::mbStrlen(
\preg_replace('~(\>).*<\/.*$~', '$1', $textFormated)
);
} else {
$nextEntity['offset'] += StrTools::mbStrlen($textFormated) - StrTools::mbStrlen($text);
}
}
unset($nextEntity);
}
}
unset($entity);
$message = \nl2br($message);
return $message;
}
private static function substringReplace(string $original, string $replacement, int $position, int $length): string
{
$startString = StrTools::mbSubstr($original, 0, $position);
$endString = StrTools::mbSubstr($original, $position + $length, StrTools::mbStrlen($original));
return $startString . $replacement . $endString;
}
/**
* Пересылает сообщения без ссылки на оригинал.
*
* @param array $data
* <pre>
* [
* 'from_peer' => '',
* 'to_peer' => '',
* 'id' => [], //Id сообщения, или нескольких сообщений
* ]
* </pre>
*
*/
public function copyMessages(array $data)
{
$data = \array_merge(
[
'from_peer' => '',
'to_peer' => '',
'id' => [],
],
$data
);
$response = $this->madelineProto->channels->getMessages(
[
'channel' => $data['from_peer'],
'id' => $data['id'],
]
);
$result = [];
if (!$response || !\is_array($response) || !\array_key_exists('messages', $response)) {
return $result;
}
foreach ($response['messages'] as $key => $message) {
$messageData = [
'message' => $message['message'] ?? '',
'peer' => $data['to_peer'],
'entities' => $message['entities'] ?? [],
];
if (self::hasMedia($message, false)) {
$messageData['media'] = $message; //MadelineProto сама достанет все media из сообщения.
$result[] = $this->madelineProto->messages->sendMedia(...$messageData);
} else {
$result[] = $this->madelineProto->messages->sendMessage(...$messageData);
}
if ($key > 0) {
delay(\random_int(300, 2000) / 1000);
}
}
return $result;
}
/**
* Загружает медиафайл из указанного сообщения в поток.
*
*
*/
public function getMedia(array $data): Response
{
$data = \array_merge(
[
'peer' => '',
'id' => [0],
'message' => [],
],
$data
);
$message = $data['message'] ?: ($this->getMessages($data))['messages'][0] ?? null;
if (!$message || $message['_'] === 'messageEmpty') {
throw new NoMediaException('Empty message');
}
if (!self::hasMedia($message, true)) {
throw new NoMediaException('Message has no media');
}
if ($message['media']['_'] !== 'messageMediaWebPage') {
$info = $this->madelineProto->getDownloadInfo($message);
} else {
$webpage = $message['media']['webpage'];
if (!empty($webpage['embed_url'])) {
return new Response(302, ['Location' => $webpage['embed_url']]);
} elseif (!empty($webpage['document'])) {
$info = $this->madelineProto->getDownloadInfo($webpage['document']);
} elseif (!empty($webpage['photo'])) {
$info = $this->madelineProto->getDownloadInfo($webpage['photo']);
} else {
return $this->getMediaPreview($data);
}
}
return $this->downloadToResponse($info);
}
/**
* Загружает превью медиафайла из указанного сообщения в поток.
*
*/
public function getMediaPreview(array $data): Response
{
$data = \array_merge(
[
'peer' => '',
'id' => [0],
'message' => [],
],
$data
);
$message = $data['message'] ?: ($this->getMessages($data))['messages'][0] ?? null;
if (!$message || $message['_'] === 'messageEmpty') {
throw new NoMediaException('Empty message');
}
if (!self::hasMedia($message, true)) {
throw new NoMediaException('Message has no media');
}
$media = match ($message['media']['_']) {
'messageMediaPhoto' => $message['media']['photo'],
'messageMediaDocument' => $message['media']['document'],
'messageMediaWebPage' => $message['media']['webpage'],
};
$thumb = null;
switch (true) {
case isset($media['sizes']):
foreach ($media['sizes'] as $size) {
if ($size['_'] === 'photoSize') {
$thumb = $size;
}
}
break;
case isset($media['thumb']['size']):
$thumb = $media['thumb'];
break;
case !empty($media['thumbs']):
foreach ($media['thumbs'] as $size) {
if ($size['_'] === 'photoSize') {
$thumb = $size;
}
}
break;
case isset($media['photo']['sizes']):
foreach ($media['photo']['sizes'] as $size) {
if ($size['_'] === 'photoSize') {
$thumb = $size;
}
}
break;
default:
throw new NoMediaException('Message has no preview');
}
if (null === $thumb) {
throw new NoMediaException('Empty preview');
}
$info = $this->madelineProto->getDownloadInfo($thumb);
if ($media['_'] === 'webPage') {
$media = $media['photo'];
}
//Фикс для LAYER 100+
//TODO: Удалить, когда снова станет доступна загрузка photoSize
if (isset($info['thumb_size'])) {
$infoFull = $this->madelineProto->getDownloadInfo($media);
$infoFull['InputFileLocation']['thumb_size'] = $info['thumb_size'];
$infoFull['size'] = $info['size'];
$infoFull['mime'] = $info['mime'] ?? 'image/jpeg';
$infoFull['name'] = 'thumb';
$infoFull['ext'] = '.jpeg';
$info = $infoFull;
}
return $this->downloadToResponse($info);
}
public function getMessages(array $data): array
{
$peerInfo = $this->madelineProto->getInfo($data['peer']);
if (\in_array($peerInfo['type'], ['channel', 'supergroup'])) {
$response = $this->madelineProto->channels->getMessages(
[
'channel' => $data['peer'],
'id' => (array) $data['id'],
]
);
} else {
$response = $this->madelineProto->messages->getMessages(['id' => (array) $data['id']]);
}
return $response;
}
/**
* Download to Amp HTTP response.
*
* @param array $info
* Any downloadable array: message, media etc...
*
*/
public function downloadToResponse(array $info): Response
{
return $this->madelineProto->downloadToResponse($info, $this->request);
}
/**
* Адаптер для стандартного метода.
*
*/
public function downloadToBrowser(array $info): Response
{
return $this->downloadToResponse($info);
}
/**
* Upload file from POST request.
* Response can be passed to 'media' field in messages.sendMedia.
*
* @throws NoMediaException
*/
public function uploadMediaForm(): array
{
if (empty($this->file)) {
throw new NoMediaException('File not found');
}
$inputFile = $this->madelineProto->uploadFromStream(
$this->file,
0,
$this->file->getMimeType(),
$this->file->getFilename()
);
$inputFile['id'] = \unpack('P', $inputFile['id'])['1'];
return [
'media' => [
'_' => 'inputMediaUploadedDocument',
'file' => $inputFile,
'attributes' => [
['_' => 'documentAttributeFilename', 'file_name' => $this->file->getFilename()]
]
]
];
}
public function setEventHandler(): void
{
Client::getWrapper($this->madelineProto)->getAPI()->setEventHandler(EventHandler::class);
Client::getWrapper($this->madelineProto)->serialize();
}
public function serialize(): void
{
Client::getWrapper($this->madelineProto)->serialize();
}
public function getUpdates(array $params): array
{
foreach ($params as $key => $value) {
$params[$key] = match($key) {
'offset', 'limit' => (int) $value,
'timeout' => (float) $value,
default => throw new InvalidArgumentException("Unknown parameter: {$key}"),
};
}
return $this->madelineProto->getUpdates($params);
}
public function setNoop(): void
{
$this->madelineProto->setNoop();
Client::getWrapper($this->madelineProto)->serialize();
}
public function setWebhook(string $url): void
{
$this->madelineProto->setWebhook($url);
Client::getWrapper($this->madelineProto)->serialize();
}
public function unsubscribeFromUpdates(?string $channel = null): array
{
$inputChannelId = null;
if ($channel) {
$id = (string) $this->madelineProto->getId($channel);
$inputChannelId = (int) \str_replace(['-100', '-'], '', $id);
if (!$inputChannelId) {
throw new InvalidArgumentException('Invalid id');
}
}
$counter = 0;
foreach (Client::getWrapper($this->madelineProto)->getAPI()->feeders as $channelId => $_) {
if ($channelId === 0) {
continue;
}
if ($inputChannelId && $inputChannelId !== $channelId) {
continue;
}
Client::getWrapper($this->madelineProto)->getAPI()->feeders[$channelId]->stop();
Client::getWrapper($this->madelineProto)->getAPI()->updaters[$channelId]->stop();
unset(
Client::getWrapper($this->madelineProto)->getAPI()->feeders[$channelId],
Client::getWrapper($this->madelineProto)->getAPI()->updaters[$channelId]
);
Client::getWrapper($this->madelineProto)->getAPI()->getChannelStates()->remove($channelId);
$counter++;
}
return [
'disabled_update_loops' => $counter,
'current_update_loops' => \count(Client::getWrapper($this->madelineProto)->getAPI()->feeders),
];
}
public function sendVideo(array $data): MadelineProto\EventHandler\Message
{
if (!empty($this->file)) {
$data['file'] = $this->file;
$data['fileName'] = $this->file->getFilename();
}
foreach (['file', 'thumb'] as $key) {
if (!empty($data[$key])) {
if (is_array($data[$key]) && !empty($data[$key]['_'])) {
$type = $data[$key]['_'];
unset($data[$key]['_']);
$data[$key] = match ($type) {
'LocalFile' => new MadelineProto\LocalFile(...$data[$key]),
'RemoteUrl' => new MadelineProto\RemoteUrl(...$data[$key]),
'BotApiFieldId' => new MadelineProto\BotApiFileId(...$data[$key]),
default => throw new InvalidArgumentException("Unknown type: {$type}"),
};
} elseif (is_string($data[$key])) {
$data[$key] = new ReadableBuffer($data[$key]);
}
}
}
if(isset($data['parseMode'])) {
$data['parseMode'] = ParseMode::from($data['parseMode']);
}
return $this->madelineProto->sendVideo(...$data);
}
}