-
Notifications
You must be signed in to change notification settings - Fork 1
/
LiveStream.php
538 lines (464 loc) · 14 KB
/
LiveStream.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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
<?php
namespace LiveStream;
use CURLFile;
use Exception;
use LiveStream\Resources\Event;
use LiveStream\Resources\RTMPKey;
use LiveStream\Resources\Account;
use LiveStream\Interfaces\Resource;
use LiveStream\Exceptions\LiveStreamException;
use LiveStream\Exceptions\InValidResourceException;
use LiveStream\Resources\Video;
class LiveStream
{
/**
* Live Stream API Base URL.
*/
const BASE_URL = 'https://livestreamapis.com/v3/';
/**
* LiveStream API HTTP Codes.
*/
const ERROR_CODES = [
400 => 'Bad Request: Your request is not properly constructed.',
401 => 'Unauthorized: Your API key is incorrect.',
403 => 'Forbidden:',
405 => 'Method Not Allowed: You tried to access a resource with an invalid method.',
406 => 'Not Acceptable: You requested a format that is not JSON.',
500 => 'Internal Server Error: We had a problem with our server. Please try again later.',
503 => 'Service Unavailable: We are temporarily offline for maintanance. Please try again later.'
];
/**
* API key.
*
* @var string
*/
private $apiKey;
/**
* Client ID.
*
* @var int
*/
private $clientId;
/**
* Scope.
*
* @var string
*/
private $scope;
/**
* Secure access token.
*
* @var string
*/
private $token;
/**
* Secure access token timestamp.
*
* @var int
*/
private $tokenTimestamp;
/**
* Class Constructor.
*
* When only an API key is provided key auth method is used. When an API
* key, client ID, and scope are provided secure token auth is used.
*
* @param string $apiKey
* @param int|null $clientId
* @param string|null $scope
* Valid scopes are: all, readonly, playback
*
* @see https://livestream.com/developers/docs/api/#authentication
*/
public function __construct(
string $apiKey,
?int $clientId = null,
?string $scope = null
)
{
$this->apiKey = $apiKey;
$this->clientId = $clientId;
$this->scope = $scope;
if ($this->clientId !== null && $this->scope !== null) {
$this->refreshToken();
}
}
/**
* Get Linked LiveStream Accounts
*
* @return array Array of LiveStream Accounts
*/
public function getAccounts(): array
{
$response = $this->request('accounts');
$accounts = [];
foreach (json_decode($response) as $account) {
$accounts[] = Account::fromObject($account);
}
return $accounts;
}
/**
* Get Specific Account
*
* @param integer $accountId
* @return Account|null
*/
public function getAccount(int $accountId): ?Account
{
$response = $this->request("accounts/$accountId");
if ($response === null) return null;
return Account::fromObject(json_decode($response));
}
/**
* Create New Event
*
* @param integer $accountId
* @param Event $event
* @return boolean
*/
public function createEvent(int $accountId, Event &$event): bool
{
$event->validate();
$response = $this->request("accounts/$accountId/events", 'post', $event);
if ($response === null) return false;
$event = Event::fromObject(json_decode($response));
return true;
}
/**
* Update Event.
*
* @param integer $accountId
* @param LiveStream\Resources\Event $event
* @return boolean
*/
public function updateEvent(int $accountId, Event $event): bool
{
$event->validate(true);
$response = $this->request("accounts/$accountId/events/$event->id", 'put', $event);
if ($response === null) return false;
return true;
}
/**
* Delete Event
*
* @param integer $accountId
* @param integer $eventId
*
* @return boolean
*/
public function deleteEvent(int $accountId, int $eventId): ?Event
{
$response = $this->request("accounts/$accountId/events/$eventId", 'delete');
if ($response === null) return null;
return Event::fromObject(json_decode($response));
}
/**
* Update Event Logo.
*
* @param integer $accountId
* @param integer $eventId
* @param string $filePath
* @return boolean
*/
public function updateEventLogo(int $accountId, int $eventId, string $filePath): Event
{
if (!in_array(mime_content_type($filePath), [
'image/png',
'image/jpg',
'image/jpeg',
'image/gif'
])) {
throw new InValidResourceException('Logo', 'poster (MIME Type must be one of image/png, image/jpg, image/gif)');
}
$response = $this->request("accounts/$accountId/events/$eventId/logo", 'put', null, null, [
'logo' => new CURLFile($filePath, mime_content_type($filePath), basename($filePath))
]);
if ($response == null) return null;
return Event::fromObject(json_decode($response));
}
/**
* Gets Events by type.
*
* @param string $type
* Valid values: draft, past, private, or upcoming.
* @param int $accountId
* @param int $page
* @param int $maxItems
* @param string $order
*
* @return array
*
* @throws \LiveStream\Exceptions\LiveStreamException
*/
protected function getEvents(
string $type,
int $accountId,
int $page,
int $maxItems,
string $order
) {
$events = [];
$response = $this->request("accounts/{$accountId}/{$type}_events", 'get', null, [
'page' => $page,
'maxItems' => $maxItems,
'order' => $order
]);
if ($response === null) return $events;
foreach (json_decode($response)->data as $event) {
$events[] = Event::fromObject($event);
}
return $events;
}
/**
* Get Draft Events
*
* @param integer $accountId
* @param integer $page
* @param integer $maxItems
* @param string $order
*
* @return array
*
* @throws \LiveStream\Exceptions\LiveStreamException
*
* @see https://livestream.com/developers/docs/api/#get-draft-events
*/
public function getDraftEvents(
int $accountId,
int $page = 1,
int $maxItems = 10,
string $order = 'desc'
): array {
return $this->getEvents('draft', $accountId, $page, $maxItems, $order);
}
/**
* Get Past Events
*
* @param integer $accountId
* @param integer $page
* @param integer $maxItems
* @param string $order
*
* @return array
*
* @throws \LiveStream\Exceptions\LiveStreamException
*
* @see https://livestream.com/developers/docs/api/#get-past-events
*/
public function getPastEvents(
int $accountId,
int $page = 1,
int $maxItems = 10,
string $order = 'desc'
): array {
return $this->getEvents('past', $accountId, $page, $maxItems, $order);
}
/**
* Get Private Events
*
* @param integer $accountId
* @param integer $page
* @param integer $maxItems
* @param string $order
*
* @return array
*
* @throws \LiveStream\Exceptions\LiveStreamException
*
* @see https://livestream.com/developers/docs/api/#get-private-events
*/
public function getPrivateEvents(
int $accountId,
int $page = 1,
int $maxItems = 10,
string $order = 'asc'
): array {
return $this->getEvents('private', $accountId, $page, $maxItems, $order);
}
/**
* Get Upcoming Events
*
* @param integer $accountId
* @param integer $page
* @param integer $maxItems
* @param string $order
*
* @return array
*
* @throws \LiveStream\Exceptions\LiveStreamException
*
* @see https://livestream.com/developers/docs/api/#get-upcoming-events
*/
public function geUpcomingEvents(
int $accountId,
int $page = 1,
int $maxItems = 10,
string $order = 'asc'
): array {
return $this->getEvents('upcoming', $accountId, $page, $maxItems, $order);
}
/**
* Get RTMP Key.
*
* @param integer $accountId
* @param integer $eventId
*
* @return \LiveStream\Resources\RTMPKey|null
*/
public function getRtmpKey(
int $accountId,
int $eventId,
bool $notifyFollowers = false,
bool $publishVideo = false,
bool $saveVideo = false
): ?RTMPKey {
$response = $this->request("accounts/$accountId/events/$eventId/rtmp", 'get', null, [
'notifyFollowers' => $notifyFollowers,
'publishVideo' => $publishVideo,
'saveVideo' => $saveVideo
]);
if ($response === null) return null;
return RTMPKey::fromObject(json_decode($response));
}
/**
* Reset RTMPKey
*
* @param integer $accountId
* @param integer $eventId
* @return \LiveStream\Resources\RTMPKey|null
*/
public function resetRtmpKey(int $accountId, int $eventId): ?RTMPKey
{
$response = $this->request("accounts/$accountId/events/$eventId/rtmp", 'put');
if ($response === null) return null;
return RTMPKey::fromObject(json_decode($response));
}
/**
* Gets current live Video for an Event, if one exists.
*
* @param int $accountId
* @param int $eventId
* @param ?int $offsetPostId
* @param ?int $older
* @param ?int $newer
*
* @return \LiveStream\Resources\Video|null
*
* @see https://livestream.com/developers/docs/api/#get-videos
*
* @throws \LiveStream\Exceptions\LiveStreamException
*/
public function getLiveVideo(
int $accountId,
int $eventId,
?int $offsetPostId = null,
?int $older = null,
?int $newer = null
): ?Video {
$video = null;
$response = $this->request("accounts/$accountId/events/$eventId/videos", 'get', null, [
'offsetPostId' => $offsetPostId,
'older' => $older,
'newer' => $newer
]);
if ($response === null) return null;
$response_data = json_decode($response);
if ($response_data->live) {
/** @var \LiveStream\Resources\Video $video */
$video = Video::fromObject($response_data->live);
}
return $video;
}
/**
* Gets contents of a Video's HLS stream (m3u8) file.
*
* Requires a secure access token.
*
* @param \LiveStream\Resources\Video $video
*
* @return string|null
* @throws \LiveStream\Exceptions\LiveStreamException
*/
public function getVideoHlsFile(Video $video): ?string {
if (!$video->m3u8) return null;
$endpoint = substr($video->m3u8, strlen(self::BASE_URL));
return $this->request($endpoint);
}
/**
* Refreshes a secure access token if invalid (5 minute life time).
*
* @see https://github.com/Livestream/livestream-api-samples/tree/master/php/secure-token-auth-sample
*/
private function refreshToken(): void
{
$now = round(microtime(true) * 1000);
if (!$this->tokenTimestamp || round(($now - $this->tokenTimestamp)/1000) > 300) {
$this->tokenTimestamp = (int) $now;
$this->token = hash_hmac('md5', "{$this->apiKey}:{$this->scope}:{$this->tokenTimestamp}", $this->apiKey);
}
}
/**
* CURL Request
*
* @param string $endpoint
* @return
*/
private function request(
string $endpoint,
string $verb = 'get',
?Resource $body = null,
?array $query = null,
?array $multipartFormData = null
): ?string {
$ch = curl_init();
if (!$ch) throw new Exception("Could not initialize CURL.");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if ($this->token && $this->clientId && $this->tokenTimestamp) {
$query['timestamp'] = $this->tokenTimestamp;
$query['clientId'] = $this->clientId;
$query['token'] = $this->token;
}
else {
curl_setopt($ch, CURLOPT_USERPWD, $this->apiKey . ':');
}
curl_setopt(
$ch,
CURLOPT_URL,
$this->get_base_url() . $endpoint . ($query ? '?' . http_build_query($query) : '')
);
if ($verb != 'get') {
if ($verb == 'post') curl_setopt($ch, CURLOPT_POST, true);
if ($verb == 'put') curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
if ($verb == 'delete') curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
if ($body) {
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: ' . $body->getContentType()
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body->getResourceBody());
} elseif ($multipartFormData) {
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: multipart/form-data'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, $multipartFormData);
}
}
$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code == 200 || $code == 201) return $response;
if ($code == 404) return null;
if ($code <= 199) throw new Exception("A CURL erorr with code '$code', has occurred.");
if ($code == 403) throw new LiveStreamException(self::ERROR_CODES[$code] . ' ' . json_decode($response)->message);
throw new LiveStreamException(self::ERROR_CODES[$code]);
}
/**
* Get Base URL.
*
* @return string
*/
private function get_base_url(): string
{
return getenv('LIB_ENV') == 'testing' ? 'http://127.0.0.1:3067/' : self::BASE_URL;
}
}