Repository navigation
Expand file tree
/
Copy pathClient.php
More file actions
351 lines (306 loc) · 11.6 KB
/
Copy pathClient.php
File metadata and controls
351 lines (306 loc) · 11.6 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
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
<?php
declare(strict_types=1);
namespace GetStream;
use GetStream\Auth\JWTGenerator;
use GetStream\Exceptions\StreamException;
use GetStream\Exceptions\StreamTaskException;
use GetStream\Exceptions\StreamTransportException;
use GetStream\Generated\CommonTrait;
use GetStream\Http\GuzzleHttpClient;
use GetStream\Http\HttpClientInterface;
/**
* Main GetStream client for interacting with the API.
*/
class Client
{
use CommonTrait;
private string $apiKey;
private string $apiSecret;
private string $baseUrl;
private HttpClientInterface $httpClient;
private JWTGenerator $jwtGenerator;
private array $defaultHeaders;
/**
* Create a new GetStream client.
*
* @param string $apiKey The API key
* @param string $apiSecret The API secret
* @param string $baseUrl The base URL for the API
* @param HttpClientInterface|null $httpClient Optional HTTP client
*/
public function __construct(
string $apiKey,
string $apiSecret,
string $baseUrl = 'https://chat.stream-io-api.com',
?HttpClientInterface $httpClient = null
) {
if (empty($apiKey)) {
throw new StreamException('API key cannot be empty');
}
if (empty($apiSecret)) {
throw new StreamException('API secret cannot be empty');
}
$this->apiKey = $apiKey;
$this->apiSecret = $apiSecret;
$this->baseUrl = rtrim($baseUrl, '/');
$this->httpClient = $httpClient ?? new GuzzleHttpClient();
$this->jwtGenerator = new JWTGenerator($apiSecret);
$this->defaultHeaders = [
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'User-Agent' => 'getstream-php-sdk/' . Constant::VERSION,
'x-stream-client' => 'stream-php-client-' . Constant::VERSION,
];
}
/**
* Get the API key.
*/
public function getApiKey(): string
{
return $this->apiKey;
}
/**
* Get the API secret.
*/
public function getApiSecret(): string
{
return $this->apiSecret;
}
/**
* Get the base URL.
*/
public function getBaseUrl(): string
{
return $this->baseUrl;
}
/**
* Get the HTTP client.
*/
public function getHttpClient(): HttpClientInterface
{
return $this->httpClient;
}
/**
* Get the JWT generator.
*/
public function getJWTGenerator(): JWTGenerator
{
return $this->jwtGenerator;
}
/**
* Verify a webhook signature using this client's API secret.
*
* Convenience wrapper around \GetStream\Webhook::verifySignature that supplies
* the secret automatically. The static method is still available.
*/
public function verifySignature(string $body, string $signature): bool
{
return \GetStream\Webhook::verifySignature($body, $signature, $this->apiSecret);
}
/**
* Verify and parse a webhook payload in one call, using this client's API secret.
*
* Handles gzip-compressed bodies transparently.
*
* @throws \GetStream\Exceptions\InvalidWebhookException on signature mismatch or parse failure
*/
public function verifyAndParseWebhook(string $body, string $signature): object
{
return \GetStream\Webhook::verifyAndParseWebhook($body, $signature, $this->apiSecret);
}
/**
* Decode + parse a Stream-delivered SQS message body.
*
* Convenience wrapper around \GetStream\Webhook::parseSqs. No signature is
* required; SQS deliveries are authenticated via AWS IAM.
*/
public function parseSqs(string $messageBody): object
{
return \GetStream\Webhook::parseSqs($messageBody);
}
/**
* Decode + parse a Stream-delivered SNS notification body.
*
* Accepts either the raw SNS HTTP envelope JSON or the pre-extracted Message
* string. Convenience wrapper around \GetStream\Webhook::parseSns. No signature
* is required; SNS deliveries are authenticated via AWS IAM.
*/
public function parseSns(string $notificationBody): object
{
return \GetStream\Webhook::parseSns($notificationBody);
}
/**
* Create a feed instance.
*
* @param string $feedGroup The feed group (e.g., 'user', 'timeline')
* @param string $feedId The feed ID (e.g., user ID)
*
* @throws StreamException
*/
public function feed(string $feedGroup, string $feedId): Feed
{
// Create a FeedsV3Client instance using the same configuration
$feedsV3Client = new FeedsV3Client($this->apiKey, $this->apiSecret, $this->baseUrl, $this->httpClient);
return new Feed($feedsV3Client, $feedGroup, $feedId);
}
/**
* Make an authenticated HTTP request to the GetStream API.
*
* @param string $method HTTP method
* @param string $path API path
* @param array $queryParams Query parameters
* @param mixed $body Request body
* @param array $pathParams Path parameters for URL substitution
*
* @return StreamResponse<mixed>
*
* @throws StreamException
*/
public function makeRequest(
string $method,
string $path,
array $queryParams = [],
mixed $body = null,
array $pathParams = []
): StreamResponse {
// Replace path parameters
foreach ($pathParams as $key => $value) {
$path = str_replace('{' . $key . '}', (string) $value, $path);
}
// Build URL
$url = $this->baseUrl . $path;
// The API reads a list query parameter as comma-separated values and ignores the key[0]= form.
foreach ($queryParams as $key => $value) {
if (is_array($value) && $value !== [] && array_is_list($value) && array_filter($value, 'is_scalar') === $value) {
if (array_filter($value, fn ($v) => is_string($v) && str_contains($v, ',')) !== []) {
throw new StreamException("Query parameter '{$key}' has a value containing a comma, which the API would split into separate values");
}
$queryParams[$key] = implode(',', $value);
}
}
// Add API key to query parameters
$queryParams['api_key'] = $this->apiKey;
// Add query parameters (there will always be at least api_key)
$url .= '?' . http_build_query($queryParams);
// Generate authentication token
$token = $this->jwtGenerator->generateServerToken();
// Prepare headers
$headers = array_merge($this->defaultHeaders, [
'Authorization' => $token,
'stream-auth-type' => 'jwt',
]);
// Check if this is an upload request (needs multipart/form-data) - like Go SDK
if ($body instanceof GeneratedModels\ImageUploadRequest || $body instanceof GeneratedModels\FileUploadRequest) {
unset($headers['Content-Type']); // Let Guzzle set multipart Content-Type
$multipart = [];
$isImage = $body instanceof GeneratedModels\ImageUploadRequest;
// File field
if ($body->file !== null) {
// Check if it's a file path that exists, otherwise treat as base64
$filePath = (string) $body->file;
$fileContent = file_exists($filePath)
? file_get_contents($filePath)
: (base64_decode($filePath, true) ?: throw new StreamException('Failed to decode base64 file data'));
$multipart[] = [
'name' => 'file',
'contents' => $fileContent,
'filename' => $isImage ? 'image.jpg' : (file_exists($filePath) ? basename($filePath) : 'file.pdf'),
];
}
// User field (JSON string)
if ($body->user !== null) {
$multipart[] = ['name' => 'user', 'contents' => json_encode($body->user)];
}
// Upload sizes (images only, JSON string)
if ($isImage && $body->uploadSizes !== null && !empty($body->uploadSizes)) {
$multipart[] = ['name' => 'upload_sizes', 'contents' => json_encode($body->uploadSizes)];
}
return $this->httpClient->request($method, $url, $headers, $multipart);
}
// Make the request
return $this->httpClient->request($method, $url, $headers, $body);
}
/**
* Generate a user token for client-side authentication.
*
* @param string $userId The user ID
* @param array $claims Additional claims
* @param int|null $expiration Token expiration in seconds (null for no expiration)
*
* @return string JWT token
*/
public function createUserToken(string $userId, array $claims = [], ?int $expiration = null): string
{
return $this->jwtGenerator->generateUserToken($userId, $claims, $expiration);
}
/**
* Create or update users.
*
* @param array $users Array of user data keyed by user ID
*
* @return StreamResponse<mixed>
*
* @throws StreamException
*/
public function upsertUsers(array $users): StreamResponse
{
$path = '/api/v2/users';
$requestData = ['users' => $users];
return $this->makeRequest('POST', $path, [], $requestData);
}
/**
* Poll the task-status endpoint until the task settles into `completed`,
* settles into `failed`, or the timeout elapses.
*
* @param string $taskId Task ID returned by an async operation
* @param int $pollIntervalSeconds Delay between polls (default 1s)
* @param int $timeoutSeconds Maximum total wait (default 60s)
*
* @return GeneratedModels\GetTaskResponse Settled task payload
*
* @throws StreamTaskException On task `status: "failed"`
* @throws StreamTransportException When polling does not settle before $timeoutSeconds
* @throws StreamException Propagated from the underlying poll request
*/
public function waitForTask(
string $taskId,
int $pollIntervalSeconds = 1,
int $timeoutSeconds = 60,
): GeneratedModels\GetTaskResponse {
$deadline = $this->now() + $timeoutSeconds;
$pollMicros = max(0, $pollIntervalSeconds) * 1_000_000;
while (true) {
$response = $this->getTask($taskId);
/** @var GeneratedModels\GetTaskResponse $task */
$task = $response->getData();
if ($task->status === 'completed') {
return $task;
}
if ($task->status === 'failed') {
$error = $task->error;
throw new StreamTaskException(
$task->taskID ?? $taskId,
$error?->type ?? '',
$error?->description ?? '',
$error?->stacktrace ?? null,
$error?->version ?? null,
);
}
if ($this->now() >= $deadline) {
throw new StreamTransportException(
sprintf('waitForTask: timed out after %ds (task %s status=%s)', $timeoutSeconds, $taskId, $task->status ?? 'unknown'),
StreamTransportException::ERROR_TYPE_TIMEOUT,
new \RuntimeException('waitForTask deadline exceeded'),
);
}
usleep($pollMicros);
}
}
/**
* Override hook for tests that need a deterministic clock.
*/
protected function now(): int
{
return time();
}
}