Lae/app/Support/EmqxSupport.php

88 lines
2.4 KiB
PHP
Raw Normal View History

2022-11-28 14:54:00 +00:00
<?php
namespace App\Support;
2022-11-28 15:14:48 +00:00
use App\Exceptions\EmqxSupportException;
2023-01-19 15:09:01 +00:00
use App\Jobs\Support\EMQXKickClientJob;
2023-01-10 13:42:27 +00:00
use Illuminate\Http\Client\ConnectionException;
2022-11-28 14:54:00 +00:00
use Illuminate\Http\Client\PendingRequest;
2023-01-19 15:24:19 +00:00
use Illuminate\Pagination\LengthAwarePaginator;
2022-11-28 14:54:00 +00:00
use Illuminate\Support\Facades\Http;
2023-01-10 13:48:11 +00:00
use Illuminate\Support\Facades\Log;
2023-01-19 15:24:19 +00:00
use Illuminate\Support\Facades\Request;
2022-11-28 14:54:00 +00:00
class EmqxSupport
{
2023-01-19 15:24:19 +00:00
private int $limit_per_page = 50;
2023-01-10 13:42:27 +00:00
/**
2023-01-19 15:09:01 +00:00
* 移除客户端
2023-01-10 13:42:27 +00:00
*/
2023-01-19 15:09:01 +00:00
public function kickClient($client_id = null, $username = null, bool $like_username = false): void
2022-11-28 14:54:00 +00:00
{
// 如果都为空,直接返回
if (empty($client_id) && empty($username)) {
return;
}
if ($client_id) {
$this->api()->delete('/clients/' . $client_id);
}
if ($username) {
2023-01-19 15:09:01 +00:00
dispatch(new EMQXKickClientJob(null, $username, $like_username));
2022-11-28 14:54:00 +00:00
}
}
2022-12-27 16:25:22 +00:00
2023-01-19 15:09:01 +00:00
public function api(): PendingRequest
2022-12-27 16:25:22 +00:00
{
return Http::baseUrl(config('emqx.api_url'))->withBasicAuth(config('emqx.api_key'), config('emqx.api_secret'));
}
/**
* @throws EmqxSupportException
*/
public function clients($params = [])
{
// merge params
$params = array_merge([
2023-01-19 15:24:19 +00:00
'limit' => $this->limit_per_page,
2022-12-27 16:25:22 +00:00
'isTrusted' => true,
], $params);
2023-01-10 13:42:27 +00:00
try {
$response = $this->api()->get('clients', $params);
2023-01-10 13:48:11 +00:00
} /** @noinspection PhpRedundantCatchClauseInspection */ catch (ConnectionException $e) {
Log::error('emqx connect failed.', [$e]);
2023-01-19 10:11:25 +00:00
throw new EmqxSupportException('EMQX API 无法连接。' . $e->getMessage());
2023-01-10 13:42:27 +00:00
}
2022-12-27 16:25:22 +00:00
if ($response->successful()) {
return $response->json();
} else {
throw new EmqxSupportException('无法获取客户端列表。');
}
}
2023-01-19 15:24:19 +00:00
/**
* @throws EmqxSupportException
*/
public function pagination($params = []): LengthAwarePaginator
{
$page = Request::input('page', 1);
$params = array_merge([
'page' => $page,
], $params);
$clients = $this->clients($params);
$data = $clients['data'];
$total = $clients['meta']['count'];
$limit = $clients['meta']['limit'];
return new LengthAwarePaginator($data, $total, $limit, $page, [
'path' => route('admin.devices.index'),
]);
}
2022-11-28 14:54:00 +00:00
}