-
Notifications
You must be signed in to change notification settings - Fork 0
/
BaseClient.php
233 lines (185 loc) · 7.46 KB
/
BaseClient.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
<?php
namespace SoureCode\OBS;
use Psr\Log\LoggerInterface;
use RuntimeException;
use SensitiveParameter;
use SoureCode\OBS\WebSocket\Embedding\Authentication;
use SoureCode\OBS\WebSocket\Embedding\ResponseStatus;
use SoureCode\OBS\WebSocket\OBSMessage;
use SoureCode\OBS\WebSocket\Receive\EventMessage;
use SoureCode\OBS\WebSocket\Receive\HelloMessage;
use SoureCode\OBS\WebSocket\Receive\IdentifiedMessage;
use SoureCode\OBS\WebSocket\Receive\RequestResponseMessage;
use SoureCode\OBS\WebSocket\Send\IdentifyMessage;
use SoureCode\OBS\WebSocket\Send\ReidentifyMessage;
use SoureCode\OBS\Protocol\Enum\EventSubscription;
use SoureCode\OBS\Protocol\Enum\WebSocketCloseCode;
use SoureCode\OBS\Protocol\Enum\WebSocketOpCode;
use SoureCode\OBS\Protocol\RequestInterface;
use SoureCode\OBS\WebSocket\Serializer\OBSMessageSerializer;
use WebSocket\Client as WebSocketClient;
use WebSocket\Connection;
use WebSocket\Exception\Exception;
use WebSocket\Message\Close;
use WebSocket\Message\Message;
use WebSocket\Message\Text;
use WebSocket\Middleware\MiddlewareInterface;
class BaseClient
{
private WebSocketClient $client;
private OBSMessageSerializer $serializer;
private ?LoggerInterface $logger = null;
public function __construct(
private readonly string $url,
?OBSMessageSerializer $obsMessageSerializer = null,
) {
$this->serializer = $obsMessageSerializer ?? new OBSMessageSerializer();
$this->client = new WebSocketClient($this->url);
}
public function send(string $message): void
{
$this->client->send(new Text($message));
}
public function hello(): OBSMessage
{
return $this->safeReceive(WebSocketOpCode::Hello, HelloMessage::class);
}
private function receive(): OBSMessage
{
$data = $this->client->receive();
if ($data instanceof Close) {
$closeStatus = $data->getCloseStatus();
if ($closeStatus !== null) {
$closeCode = WebSocketCloseCode::tryFrom($closeStatus);
if ($closeCode === null) {
throw new RuntimeException(message: sprintf("Connection closed unexpectedly with %d", $closeStatus));
}
throw new RuntimeException(message: sprintf("Connection closed unexpectedly with %d - %s", $closeCode->value, $closeCode->name));
}
throw new RuntimeException('Connection closed unexpectedly');
}
if (!$data instanceof Text) {
throw new RuntimeException('Unexpected message type');
}
$content = $data->getContent();
$this->logger?->debug('Received message', [
'content' => $content,
'payload' => $data->getPayload(),
'timestamp' => $data->getTimestamp(),
'length' => $data->getLength(),
'op' => $data->getOpcode(),
]);
return $this->serializer->deserialize($content);
}
public function identify(#[SensitiveParameter] $plainPassword, Authentication $authentication, ?EventSubscription $eventSubscriptions = EventSubscription::None): OBSMessage
{
$auth = base64_encode(hash('sha256', $plainPassword . $authentication->salt, true));
$response = base64_encode(hash('sha256', $auth . $authentication->challenge, true));
$message = new IdentifyMessage(1, $response, $eventSubscriptions);
$obsMessage = new OBSMessage(WebSocketOpCode::Identify, $message);
$this->send($this->serializer->serialize($obsMessage));
return $this->identified();
}
public function identified(): OBSMessage
{
return $this->safeReceive(WebSocketOpCode::Identified, IdentifiedMessage::class);
}
public function reidentify(?EventSubscription $eventSubscriptions = EventSubscription::None): OBSMessage
{
$message = new ReidentifyMessage($eventSubscriptions);
$obsMessage = new OBSMessage(WebSocketOpCode::Reidentify, $message);
$this->send($this->serializer->serialize($obsMessage));
return $this->identified();
}
public function request(RequestInterface $request): OBSMessage
{
$this->send($this->serializer->serializeRequest($request));
return $this->safeReceive(WebSocketOpCode::RequestResponse, RequestResponseMessage::class);
}
private function safeReceive(WebSocketOpCode $code, string $className): OBSMessage
{
while (true) {
$obsMessage = $this->receive();
if ($obsMessage->op === $code && $obsMessage->d instanceof $className) {
if ($obsMessage->d instanceof RequestResponseMessage) {
$status = $obsMessage->d->requestStatus;
if (!$status->result) {
throw new RuntimeException(message: sprintf('Request failed with %d - %s', $status->code, $status->comment));
}
}
return $obsMessage;
}
}
}
public function authenticate(#[SensitiveParameter] $plainPassword, ?EventSubscription $eventSubscriptions = EventSubscription::None): void
{
if (!$this->client->isConnected()) {
$this->client->connect();
}
$helloMessage = $this->hello();
if ($helloMessage->d->authentication) {
$this->identify($plainPassword, $helloMessage->d->authentication, $eventSubscriptions);
}
}
/**
* Receive events from the WebSocket connection until an event is received, everything else is ignored.
*/
public function pollEvent(): EventMessage
{
while (true) {
$obsMessage = $this->receive();
if ($obsMessage->op === WebSocketOpCode::Event) {
return $obsMessage->d;
}
}
}
public function addMiddleware(MiddlewareInterface $middleware): static
{
$this->client->addMiddleware($middleware);
return $this;
}
public function setLogger(LoggerInterface $logger): static
{
$this->logger = $logger;
$this->client->setLogger($logger);
return $this;
}
/**
* @param callable(OBSMessage, BaseClient, WebSocketClient, Connection, Message): void $callback
* @return $this
*/
public function on(callable $callback): static
{
$this->client->onText(function (WebSocketClient $client, Connection $connection, Message $message) use ($callback) {
$obsMessage = $this->serializer->deserialize($message->getContent());
$callback($obsMessage, $this, $client, $connection, $message);
});
return $this;
}
/**
* @param callable(BaseClient, WebSocketClient, ?Connection, Exception): void $callback
* @return $this
*/
public function onError(callable $callback): static
{
$this->client->onError(function (WebSocketClient $client, Connection|null $connection, Exception $exception) use ($callback) {
$callback($this, $client, $connection, $exception);
});
return $this;
}
/**
* @param callable(BaseClient, WebSocketClient, Connection, Close): void $callback
* @return $this
*/
public function onClose(callable $callback): static
{
$this->client->onClose(function (WebSocketClient $client, Connection $connection, Close $message) use ($callback) {
$callback($this, $client, $connection, $message);
});
return $this;
}
public function start(): void
{
$this->client->start();
}
}