-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnifiClient.php
More file actions
190 lines (173 loc) · 6.39 KB
/
UnifiClient.php
File metadata and controls
190 lines (173 loc) · 6.39 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
<?php
declare(strict_types=1);
namespace SkyDiablo\UnifiApiClient;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\UriInterface;
use React\Http\Browser;
use React\Http\Message\ResponseException;
use React\Http\Message\Uri;
use React\Promise\PromiseInterface;
use React\Socket\Connector;
use React\Socket\ConnectorInterface;
class UnifiClient
{
protected Browser $httpClient;
private ?string $unifiSession = null;
private ?string $csrfToken = null;
public function __construct(
string $uri,
protected string $username,
protected string $password,
ConnectorInterface $connector = null
)
{
$this->httpClient = (new Browser($connector ?? new Connector(
[
'tls' => [
'verify_peer' => false,
'verify_peer_name' => false
],
]
)
))->withBase(rtrim($uri, '/') . '/');
}
protected function defaultHeader(array $header = []): array
{
return $header + [
'Content-Type' => 'application/json;charset=utf-8',
'Accept' => 'application/json, text/plain, */*',
'Cache-Control' => 'no-cache',
] + ($this->unifiSession ? ['Cookie' => sprintf('unifises=%s; csrf_token=%s', $this->unifiSession, $this->csrfToken)] : [])
+ ($this->csrfToken ? ['X-Csrf-Token' => $this->csrfToken] : []);
}
/**
* @param ApiEndpoint $endpoint
* @param array $pathParams replace placeholder like "{id}" if given array ['id' => 1]
* @return Uri
*/
protected function url(ApiEndpoint $endpoint, array $pathParams = []): UriInterface
{
$path = str_replace(
array_map(function ($key) {
return sprintf('{%s}', $key);
}, array_keys($pathParams)),
$pathParams,
$endpoint->value
);
return new Uri(ltrim($path, '/'));
}
protected function body($data): false|string
{
return json_encode($data);
}
/**
* @param ResponseInterface $response
* @return array
*/
protected function decode(ResponseInterface $response): array
{
$ct = $response->getHeader('Content-Type')[0] ?? '';
if (str_contains($ct, 'application/json')) {
return json_decode($response->getBody()->getContents(), true);
}
return [];
}
/**
* @param array $data
* @param ApiEndpoint $endpoint
* @param array $pathParams
* @param array $queryParams
* @param bool $autoLogin
* @return PromiseInterface<array>
*/
public function post(array $data, ApiEndpoint $endpoint, array $pathParams = [], array $queryParams = [], bool $autoLogin = true): PromiseInterface
{
$uri = $this->addQueryParams($queryParams, $this->url($endpoint, $pathParams));
return $this->httpClient->post(
$uri,
$this->defaultHeader(),
$this->body($data)
)
->then(fn(ResponseInterface $response) => $this->parseSetCookies($response)->decode($response))
->catch(function (ResponseException $e) use ($autoLogin, $endpoint, $pathParams, $queryParams, $data) {
if ($autoLogin) {
return $this->login($this->username, $this->password)->then(function () use ($endpoint, $pathParams, $queryParams, $data) {
return $this->post($data, $endpoint, $pathParams, $queryParams, false);
});
}
throw $e;
});
}
/**
* @param ApiEndpoint $endpoint
* @param array $pathParams
* @param array $queryParams
* @param bool $autoLogin
* @return PromiseInterface<array>
*/
public function get(ApiEndpoint $endpoint, array $pathParams = [], array $queryParams = [], bool $autoLogin = true): PromiseInterface
{
$uri = $this->addQueryParams($queryParams, $this->url($endpoint, $pathParams));
return $this->httpClient->get(
$uri,
$this->defaultHeader()
)
->then(fn(ResponseInterface $response) => $this->parseSetCookies($response)->decode($response))
->catch(function (ResponseException $e) use ($autoLogin, $endpoint, $pathParams, $queryParams) {
if ($autoLogin) {
return $this->login($this->username, $this->password)->then(function () use ($endpoint, $pathParams, $queryParams) {
return $this->get($endpoint, $pathParams, $queryParams, false);
});
}
throw $e;
});
}
protected function addQueryParams(array $queryParams, Uri $uri): UriInterface
{
return $uri->withQuery(trim(sprintf('%s&%s', $uri->getQuery(), http_build_query($queryParams)), '&'));
}
protected function login(string $username, string $password): PromiseInterface
{
$params = [
'username' => $username,
'password' => $password,
'strict' => true,
'remember' => false,
];
return $this->post($params, ApiEndpoint::LOGIN, autoLogin: false);
}
//parse the http header to extract session key and csrf token
public function parseSetCookies(ResponseInterface $response): self
{
$parser = function ($cookie) {
$result = [];
foreach (explode(';', $cookie) as $part) {
if (str_contains($part, '=')) { //key=value
[$key, $value] = explode('=', $part, 2);
$result[trim($key)] = trim($value);
} else {
$result[trim($part)] = true;
}
}
return $result;
};
foreach ($response->getHeader('Set-Cookie') as $header) {
$cookieParts = $parser($header);
if (isset($cookieParts['unifises'])) {
$this->unifiSession = $cookieParts['unifises'];
}
if (isset($cookieParts['csrf_token'])) {
$this->csrfToken = $cookieParts['csrf_token'];
}
}
return $this;
}
public function logout(): PromiseInterface
{
return $this->post([], ApiEndpoint::LOGOUT)->then(function (array $data) {
$this->unifiSession = null;
$this->csrfToken = null;
return $data;
});
}
}