1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace Sysbot\Telegram\Helpers; |
5
|
|
|
|
6
|
|
|
|
7
|
|
|
use GuzzleHttp\Client; |
8
|
|
|
use GuzzleHttp\Exception\RequestException; |
9
|
|
|
use GuzzleHttp\Promise\PromiseInterface; |
10
|
|
|
use Psr\Http\Message\ResponseInterface; |
11
|
|
|
use Sysbot\Telegram\Exceptions\TelegramAPIException; |
12
|
|
|
use Sysbot\Telegram\Exceptions\TelegramBadRequestException; |
13
|
|
|
use Sysbot\Telegram\Exceptions\TelegramForbiddenException; |
14
|
|
|
use Sysbot\Telegram\Exceptions\TelegramNotFoundException; |
15
|
|
|
use Sysbot\Telegram\Exceptions\TelegramUnauthorizedException; |
16
|
|
|
|
17
|
|
|
trait FileDownloader |
18
|
|
|
{ |
19
|
|
|
|
20
|
|
|
public function downloadFile(string $remotePath): PromiseInterface |
21
|
|
|
{ |
22
|
|
|
/** @var Client $client */ |
23
|
|
|
$client = $this->client; |
24
|
|
|
$uri = sprintf('/file/bot%s/%s', $this->token, $remotePath); |
25
|
|
|
return $client->getAsync($uri)->then( |
26
|
|
|
function (ResponseInterface $response) { |
27
|
|
|
return $response->getBody(); |
28
|
|
|
}, |
29
|
|
|
function (RequestException $e) { |
30
|
|
|
$message = sprintf( |
31
|
|
|
'An unknown error occurred when trying to fetch the file (%s): %s', |
32
|
|
|
$e->getCode(), |
33
|
|
|
$e->getMessage() |
34
|
|
|
); |
35
|
|
|
if (!$e->hasResponse()) { |
36
|
|
|
throw new TelegramAPIException($message); |
37
|
|
|
} |
38
|
|
|
$data = json_decode($e->getResponse()?->getBody()); |
39
|
|
|
if (empty($data)) { |
40
|
|
|
throw new TelegramAPIException($message); |
41
|
|
|
} |
42
|
|
|
match ($data->error_code) { |
43
|
|
|
400 => throw new TelegramBadRequestException($data->description), |
44
|
|
|
401 => throw new TelegramUnauthorizedException('Token invalid or expired'), |
45
|
|
|
403 => throw new TelegramForbiddenException($data->description), |
46
|
|
|
404 => throw new TelegramNotFoundException($data->description), |
47
|
|
|
default => throw new TelegramAPIException( |
48
|
|
|
sprintf( |
49
|
|
|
'Telegram API returned an error (%s): %s', |
50
|
|
|
$data->error_code ?? 'Unknown', |
51
|
|
|
$data->description ?? 'Unknown' |
52
|
|
|
) |
53
|
|
|
) |
54
|
|
|
}; |
55
|
|
|
} |
56
|
|
|
); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
} |