-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy pathOpenTok.php
1394 lines (1263 loc) · 60.1 KB
/
OpenTok.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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace OpenTok;
use DateTimeImmutable;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Encoding\ChainedFormatter;
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Signer\Rsa\Sha256;
use Lcobucci\JWT\Token\Builder;
use OpenTok\Util\Client;
use OpenTok\Util\Validators;
use OpenTok\Exception\InvalidArgumentException;
use OpenTok\Exception\UnexpectedValueException;
use Ramsey\Uuid\Uuid;
use Vonage\JWT\TokenGenerator;
/**
* Contains methods for creating OpenTok sessions, generating tokens, and working with archives.
* <p>
* To create a new OpenTok object, call the OpenTok() constructor with your OpenTok API key
* and the API secret for your <a href="https://tokbox.com/account">OpenTok Video API account</a>. Do not
* publicly share your API secret. You will use it with the OpenTok() constructor (only on your web
* server) to create OpenTok sessions.
*
* If you set api_key to a VONAGE_APPLICATION_ID and api_secret to a VONAGE_PRIVATE_KEY_PATH, the SDK
* will hit Vonage Video with Vonage Auth instead.
* <p>
* Be sure to include the entire OpenTok server SDK on your web server.
*/
class OpenTok
{
/** @internal */
private $apiKey;
/** @internal */
private $apiSecret;
/** @internal */
private $client;
/**
* @var bool
* Override to determine whether to hit Vonage servers with Vonage Auth in requests
*/
private $vonage = false;
/**
* @var array
* @internal
*/
public $options;
/** @internal */
public function __construct($apiKey, $apiSecret, $options = array())
{
$apiUrl = 'https://api.opentok.com';
if (Validators::isVonageKeypair($apiKey, $apiSecret)) {
$this->vonage = true;
$apiUrl = 'https://video.api.vonage.com';
}
// unpack optional arguments (merging with default values) into named variables
$defaults = array(
'apiUrl' => $apiUrl,
'client' => null,
'timeout' => null, // In the future we should set this to 2
);
$this->options = array_merge($defaults, array_intersect_key($options, $defaults));
list($apiUrl, $client, $timeout) = array_values($this->options);
Validators::validateApiUrl($apiUrl);
Validators::validateClient($client);
Validators::validateDefaultTimeout($timeout);
$this->client = isset($client) ? $client : new Client();
if (!$this->client->isConfigured()) {
$this->client->configure(
$apiKey,
$apiSecret,
$apiUrl,
array_merge(['timeout' => $timeout], $this->options)
);
}
$this->apiKey = $apiKey;
$this->apiSecret = $apiSecret;
}
/**
* Creates a token for connecting to an OpenTok session.
*
* In order to authenticate a user
* connecting to an OpenTok session, the client passes a token when connecting to the session.
* <p>
* For testing, you generate tokens or by logging in to your
* <a href="https://tokbox.com/account">OpenTok Video API account</a>.
*
* @param string $sessionId The session ID corresponding to the session to which the user
* will connect.
*
* @param array $payload This array defines options for the token. This array includes the
* following keys, all of which are optional:
*
* <ul>
*
* <li><code>'role'</code> (string) — One of the constants defined in the RoleConstants
* class. The default role is publisher</li>
*
* <li><code>'expireTime'</code> (int) — The timestamp for when the token expires,
* in milliseconds since the Unix epoch. The default expiration time is 24 hours
* after the token creation time. The maximum expiration time is 30 days after the
* token creation time.</li>
*
* <li><code>'data'</code> (string) — A string containing connection metadata
* describing the end-user. For example, you can pass the user ID, name, or other data
* describing the end-user. The length of the string is limited to 1000 characters.
* This data cannot be updated once it is set.</li>
*
* <li><code>initialLayoutClassList</code> (array) — An array of class names (strings)
* to be used as the initial layout classes for streams published by the client. Layout
* classes are used in customizing the layout of videos in
* <a href="https://tokbox.com/developer/guides/broadcast/live-streaming/">live streaming
* broadcasts</a> and
* <a href="https://tokbox.com/developer/guides/archiving/layout-control.html">composed
* archives</a>.
* </li>
*
* </ul>
*
* @param bool $legacy By default, OpenTok uses SHA256 JWTs for authentication. Switching
* legacy to true will create a T1 token for backwards compatibility.
*
* @return string The token string.
*/
public function generateToken(string $sessionId, array $payload = array(), bool $legacy = false): string
{
if ($legacy) {
return $this->returnLegacyToken($sessionId, $payload);
}
$issuedAt = new \DateTimeImmutable('@' . time());
$defaults = [
'iss' => $this->apiKey,
'iat' => $issuedAt->getTimestamp(),
'session_id' => $sessionId,
'role' => Role::PUBLISHER,
'ist' => 'project',
'nonce' => mt_rand(),
'scope' => 'session.connect'
];
$payload = array_merge($defaults, array_intersect_key($payload, $defaults));
return JWT::encode($payload, $this->apiSecret, 'HS256');
}
private function returnLegacyToken(string $sessionId, array $options = []): string
{
$defaults = array(
'role' => Role::PUBLISHER,
'expireTime' => null,
'data' => null,
'initialLayoutClassList' => array(''),
);
$options = array_merge($defaults, array_intersect_key($options, $defaults));
list($role, $expireTime, $data, $initialLayoutClassList) = array_values($options);
// additional token data
$createTime = time();
$nonce = microtime(true) . mt_rand();
// validate arguments
Validators::validateSessionIdBelongsToKey($sessionId, $this->apiKey);
Validators::validateRole($role);
Validators::validateExpireTime($expireTime, $createTime);
Validators::validateData($data);
Validators::validateLayoutClassList($initialLayoutClassList, 'JSON');
$dataString = "session_id=$sessionId&create_time=$createTime&role=$role&nonce=$nonce" .
(($expireTime) ? "&expire_time=$expireTime" : '') .
(($data) ? "&connection_data=" . urlencode($data) : '') .
((!empty($initialLayoutClassList)) ? "&initial_layout_class_list=" . urlencode(join(" ", $initialLayoutClassList)) : '');
$sig = $this->signString($dataString, $this->apiSecret);
return "T1==" . base64_encode("partner_id=$this->apiKey&sig=$sig:$dataString");
}
/**
* Creates a new OpenTok session and returns the session ID, which uniquely identifies
* the session.
* <p>
* For example, when using the OpenTok JavaScript library, use the session ID when calling the
* <a href="http://tokbox.com/opentok/libraries/client/js/reference/OT.html#initSession">
* OT.initSession()</a> method (to initialize an OpenTok session).
* <p>
* OpenTok sessions do not expire. However, authentication tokens do expire (see the
* generateToken() method). Also note that sessions cannot explicitly be destroyed.
* <p>
* A session ID string can be up to 255 characters long.
* <p>
* Calling this method results in an OpenTokException in the event of an error.
* Check the error message for details.
* <p>
* You can also create a session by logging in to your
* <a href="https://tokbox.com/account">OpenTok Video API account</a>.
*
* @param array $options (Optional) This array defines options for the session. The array includes
* the following keys (all of which are optional):
*
* <ul>
*
* <li><code>'archiveMode'</code> (ArchiveMode) — Whether the session is automatically
* archived (<code>ArchiveMode::ALWAYS</code>) or not (<code>ArchiveMode::MANUAL</code>).
* By default, the setting is <code>ArchiveMode.MANUAL</code>, and you must call the
* <code>OpenTok->startArchive()</code> method to start archiving. To archive the session
* (either automatically or not), you must set the <code>mediaMode</code> key to
* <code>MediaMode::ROUTED</code>.</li>
*
* <li><code>'e2ee'</code> (Boolean) — Whether to enable
* <a href="https://tokbox.com/developer/guides/end-to-end-encryption">end-to-end encryption</a>
* for a routed session.</li>
*
* <li><code>archiveName</code> (String) — Name of the archives in auto archived sessions</li>
*
* <li><code>archiveResolution</code> (Enum) — Resolution of the archives in
* auto archived sessions. Can be one of "480x640", "640x480", "720x1280", "1280x720", "1080x1920", "1920x1080"</li>
*
* <li><code>'location'</code> (String) — An IP address that the OpenTok servers
* will use to situate the session in its global network. If you do not set a location hint,
* the OpenTok servers will be based on the first client connecting to the session.</li>
*
* <li><code>'mediaMode'</code> (MediaMode) — Whether the session will transmit
* streams using the OpenTok Media Router (<code>MediaMode.ROUTED</code>) or not
* (<code>MediaMode.RELAYED</code>). By default, the <code>mediaMode</code> property
* is set to <code>MediaMode.RELAYED</code>.
*
* <p>
* With the <code>mediaMode</code> parameter set to <code>MediaMode.RELAYED</code>, the
* session will attempt to transmit streams directly between clients. If clients cannot
* connect due to firewall restrictions, the session uses the OpenTok TURN server to relay
* audio-video streams.
*
* <p>
* The
* <a href="https://tokbox.com/opentok/tutorials/create-session/#media-mode" target="_top">
* OpenTok Media Router</a> provides the following benefits:
*
* <ul>
* <li>The OpenTok Media Router can decrease bandwidth usage in multiparty sessions.
* (When the <code>mediaMode</code> parameter is set to <code>MediaMode.ROUTED</code>,
* each client must send a separate audio-video stream to each client subscribing to
* it.)</li>
* <li>The OpenTok Media Router can improve the quality of the user experience through
* recovery</a>. With these features, if a client's connectivity degrades to a degree
* that it does not support video for a stream it's subscribing to, the video is dropped
* on that client (without affecting other clients), and the client receives audio only.
* If the client's connectivity improves, the video returns.</li>
* <li>The OpenTok Media Router supports the
* <a href="https://tokbox.com/opentok/tutorials/archiving" target="_top">archiving</a>
* feature, which lets you record, save, and retrieve OpenTok sessions.</li>
* </ul>
*
* </ul>
*
* @return \OpenTok\Session A Session object representing the new session. Call the
* <code>getSessionId()</code> method of this object to get the session ID. For example,
* when using the OpenTok.js library, use this session ID when calling the
* <code>OT.initSession()</code> method.
*/
public function createSession($options = array())
{
if (
array_key_exists('archiveMode', $options) &&
$options['archiveMode'] !== ArchiveMode::MANUAL
) {
if (
array_key_exists('mediaMode', $options) &&
$options['mediaMode'] !== MediaMode::ROUTED
) {
throw new InvalidArgumentException('A session must be routed to be archived.');
} else {
$options['mediaMode'] = MediaMode::ROUTED;
}
}
if (array_key_exists('e2ee', $options) && $options['e2ee']) {
if (array_key_exists('mediaMode', $options) && $options['mediaMode'] !== MediaMode::ROUTED) {
throw new InvalidArgumentException('MediaMode must be routed in order to enable E2EE');
}
if (array_key_exists('archiveMode', $options) && $options['archiveMode'] === ArchiveMode::ALWAYS) {
throw new InvalidArgumentException('ArchiveMode cannot be set to always when using E2EE');
}
$options['e2ee'] = 'true';
}
// unpack optional arguments (merging with default values) into named variables
$defaults = array(
'mediaMode' => MediaMode::RELAYED,
'archiveMode' => ArchiveMode::MANUAL,
'location' => null,
'e2ee' => 'false',
'archiveName' => null,
'archiveResolution' => null
);
// Have to hack this because the default system in these classes needs total refactor
$resolvedArchiveMode = array_merge($defaults, array_intersect_key($options, $defaults));
if ($resolvedArchiveMode['archiveMode'] === ArchiveMode::ALWAYS) {
$defaults['archiveResolution'] = '640x480';
}
$options = array_merge($defaults, array_intersect_key($options, $defaults));
// Have to hack this because the default system in these classes needs total refactor
if ($options['archiveName'] === null) {
unset($options['archiveName']);
}
if ($options['archiveResolution'] === null) {
unset($options['archiveResolution']);
}
list($mediaMode, $archiveMode, $location, $e2ee) = array_values($options);
// validate arguments
Validators::validateMediaMode($mediaMode);
Validators::validateArchiveMode($archiveMode);
Validators::validateAutoArchiveMode($archiveMode, $options);
Validators::validateLocation($location);
// make API call
$sessionXml = $this->client->createSession($options);
// check response
$sessionId = $sessionXml->Session->session_id;
if (!$sessionId) {
$errorMessage = 'Failed to create a session. Server response: ' . $sessionXml;
throw new UnexpectedValueException($errorMessage);
}
return new Session($this, (string)$sessionId, array(
'location' => $location,
'mediaMode' => $mediaMode,
'archiveMode' => $archiveMode,
'e2ee' => $e2ee
));
}
/**
* Starts an Experience Composer renderer for an OpenTok session.
* For more information, see the
* <a href="https://tokbox.com/developer/guides/experience-composer">Experience Composer
* developer guide</a>.
*
* @param $sessionId (string) The session ID of the OpenTok session that will include the Experience Composer stream.
*
* @param $token (string) A valid OpenTok token with a Publisher role and (optionally) connection data to be associated with the output stream.
*
* @param $url (string) A publicly reachable URL controlled by the customer and capable of generating the content to be rendered without user intervention.
* The minimum length of the URL is 15 characters and the maximum length is 2048 characters.
*
* @param $maxDuration (int) (optional) The maximum time allowed for the Experience Composer, in seconds. After this time, it is stopped
* automatically, if it is still running. The maximum value is 36000 (10 hours), the minimum value is 60 (1 minute), and the default value is 7200 (2 hours).
* When the Experience Composer ends, its stream is unpublished and an event is posted to the callback URL, if configured in the Account Portal.
*
* @param $resolution (string) (optional) The resolution of the Experience Composer, either "640x480" (SD landscape), "480x640" (SD portrait), "1280x720" (HD landscape),
* "720x1280" (HD portrait), "1920x1080" (FHD landscape), or "1080x1920" (FHD portrait). By default, this resolution is "1280x720" (HD landscape, the default).
*
* @param $properties (array) (optional) The initial configuration of Publisher properties for the composed output stream.
* <ul>
* <li><code>name</code> (String) (optional) — Serves as the name of the composed output stream which is published to the session. The name must have a minimum length of 1 and
* a maximum length of 200.
* </li>
* </ul>
*
* @return \OpenTok\Render The render object, which includes properties defining the render, including the render ID.
*/
public function startRender(
$sessionId,
$token,
$url,
$maxDuration,
$resolution,
$properties
): Render {
$arguments = [
'sessionId' => $sessionId,
'token' => $token,
'url' => $url,
'maxDuration' => $maxDuration,
'resolution' => $resolution,
'properties' => $properties
];
$defaults = [
'maxDuration' => 1800,
'resolution' => '1280x720',
];
$payload = array_merge($defaults, $arguments);
Validators::validateSessionId($payload['sessionId']);
$render = $this->client->startRender($payload);
return new Render($render);
}
/**
* Returns a list of Experience Composer renderers for an OpenTok project.
*
* @param int $offset
* @param int $count
*
* @return mixed
*/
public function listRenders(int $offset = 0, int $count = 50)
{
$queryPayload = [
'offset' => $offset,
'count' => $count
];
return $this->client->listRenders($queryPayload);
}
/**
* Stops an existing render.
*
* @param $renderId
*
* @return mixed
*/
public function stopRender($renderId)
{
return $this->client->stopRender($renderId);
}
/**
* Fetch an existing render to view status. Status can be one of:
* <ul>
* <li><code>starting</code> — The Vonage Video API platform is in the process of connecting to the remote application at the URL provided. This is the initial state.</li>
* <li><code>started</code> — The Vonage Video API platform has succesfully connected to the remote application server, and is republishing that media into the Vonage Video API platform.</li>
* <li><code>stopped</code> — The Render has stopped.</li>
* <li><code>failed</code> — An error occurred and the Render could not proceed. It may occur at startup if the opentok server cannot connect to the remote application server or republish the stream. It may also occur at point during the rendering process due to some error in the Vonage Video API platform.</li>
* </ul>
*
* @param $renderId
*
* @return Render
*/
public function getRender($renderId): Render
{
$renderPayload = $this->client->getRender($renderId);
return new Render($renderPayload);
}
/**
* Starts archiving an OpenTok session.
* <p>
* Clients must be actively connected to the OpenTok session for you to successfully start
* recording an archive.
* <p>
* You can only record one archive at a time for a given session. You can only record archives
* of sessions that use the OpenTok Media Router (sessions with the
* <a href="http://tokbox.com/opentok/tutorials/create-session/#media-mode">media mode</a>
* set to routed); you cannot archive sessions with the media mode set to relayed.
* <p>
* For more information on archiving, see the
* <a href="https://tokbox.com/opentok/tutorials/archiving/">OpenTok archiving</a> programming
* guide.
*
* @param String $sessionId The session ID of the OpenTok session to archive.
* @param array $options (Optional) This array defines options for the archive. The array
* includes the following keys (all of which are optional):
*
* <ul>
*
* <li><code>'name'</code> (String) — The name of the archive. You can use this name to
* identify the archive. It is a property of the Archive object, and it is a property of
* archive-related events in the OpenTok client SDKs.</li>
*
* <li><code>'hasVideo'</code> (Boolean) — Whether the archive will record video
* (true, the default) or not (false). If you set both <code>hasAudio</code> and
* <code>hasVideo</code> to false, the call to the <code>startArchive()</code> method results
* in an error.</li>
*
* <li><code>'streamMode'</code> (String) — Whether streams included in the archive are
* selected automatically (<code>StreamMode.AUTO</code>, the default) or manually
* (<code>StreamMode.MANUAL</code>). When streams are selected automatically
* (<code>StreamMode.AUTO</code>), all streams in the session can be included in the archive.
* When streams are selected manually (<code>StreamMode.MANUAL</code>), you specify streams
* to be included based on calls to the <code>Archive.addStreamToArchive()</code> and
* <code>Archive.removeStreamFromArchive()</code>. methods. With manual mode, you can specify
* whether a stream's audio, video, or both are included in the archive. In both automatic and
* manual modes, the archive composer includes streams based on
* <a href="https://tokbox.com/developer/guides/archive-broadcast-layout/#stream-prioritization-rules">stream
* prioritization rules</a>.</li>
*
* <li><code>'hasAudio'</code> (Boolean) — Whether the archive will record audio
* (true, the default) or not (false). If you set both <code>hasAudio</code> and
* <code>hasVideo</code> to false, the call to the <code>startArchive()</code> method results
* in an error.</li>
*
* <li><code>'multiArchiveTag'</code> (String) (Optional) — Set this to support recording multiple archives
* for the same session simultaneously. Set this to a unique string for each simultaneous archive of an ongoing
* session. You must also set this option when manually starting an archive
* that is {https://tokbox.com/developer/guides/archiving/#automatic automatically archived}.
* Note that the `multiArchiveTag` value is not included in the response for the methods to
* {https://tokbox.com/developer/rest/#listing_archives list archives} and
* {https://tokbox.com/developer/rest/#retrieve_archive_info retrieve archive information}.
* If you do not specify a unique `multiArchiveTag`, you can only record one archive at a time for a given session.
* {https://tokbox.com/developer/guides/archiving/#simultaneous-archives See Simultaneous archives}.</li>
*
* <li><code>'outputMode'</code> (OutputMode) — Whether all streams in the
* archive are recorded to a single file (<code>OutputMode::COMPOSED</code>, the default)
* or to individual files (<code>OutputMode::INDIVIDUAL</code>).</li>
*
* <li><code>'resolution'</code> (String) — The resolution of the archive, either "640x480" (SD landscape,
* the default), "1280x720" (HD landscape), "1920x1080" (FHD landscape), "480x640" (SD portrait), "720x1280"
* (HD portrait), or "1080x1920" (FHD portrait). This property only applies to composed archives. If you set
* this property and set the outputMode property to "individual", a call to the method
* results in an error.</li>
* </ul>
*
* @return Archive The Archive object, which includes properties defining the archive, including
* the archive ID.
*/
public function startArchive(string $sessionId, $options = []): Archive
{
// support for deprecated method signature, remove in v3.0.0 (not before)
if (!is_array($options)) {
trigger_error(
'Archive options passed as a string is deprecated, please pass an array with a name key',
E_USER_DEPRECATED
);
$options = array('name' => $options);
}
// unpack optional arguments (merging with default values) into named variables
$defaults = array(
'name' => null,
'hasVideo' => true,
'hasAudio' => true,
'outputMode' => OutputMode::COMPOSED,
'resolution' => null,
'streamMode' => StreamMode::AUTO,
);
// Horrible hack to workaround the defaults behaviour
if (isset($options['maxBitrate'])) {
$maxBitrate = $options['maxBitrate'];
}
$options = array_merge($defaults, array_intersect_key($options, $defaults));
list($name, $hasVideo, $hasAudio, $outputMode, $resolution, $streamMode) = array_values($options);
if (isset($maxBitrate)) {
$options['maxBitrate'] = $maxBitrate;
}
Validators::validateSessionId($sessionId);
Validators::validateArchiveName($name);
if ($resolution) {
Validators::validateResolution($resolution);
}
Validators::validateArchiveHasVideo($hasVideo);
Validators::validateArchiveHasAudio($hasAudio);
Validators::validateArchiveOutputMode($outputMode);
Validators::validateHasStreamMode($streamMode);
if ((is_null($resolution) || empty($resolution)) && $outputMode === OutputMode::COMPOSED) {
$options['resolution'] = "640x480";
} elseif ((is_null($resolution) || empty($resolution)) && $outputMode === OutputMode::INDIVIDUAL) {
unset($options['resolution']);
} elseif (!empty($resolution) && $outputMode === OutputMode::INDIVIDUAL) {
$errorMessage = "Resolution can't be specified for Individual Archives";
throw new UnexpectedValueException($errorMessage);
} elseif (!empty($resolution) && $outputMode === OutputMode::COMPOSED && !is_string($resolution)) {
$errorMessage = "Resolution must be a valid string";
throw new UnexpectedValueException($errorMessage);
}
$archiveData = $this->client->startArchive($sessionId, $options);
return new Archive($archiveData, array( 'client' => $this->client ));
}
/**
* Stops an OpenTok archive that is being recorded.
* <p>
* Archives automatically stop recording after 120 minutes or when all clients have disconnected
* from the session being archived.
*
* @param String $archiveId The archive ID of the archive you want to stop recording.
* @return Archive The Archive object corresponding to the archive being stopped.
*/
public function stopArchive($archiveId)
{
Validators::validateArchiveId($archiveId);
$archiveData = $this->client->stopArchive($archiveId);
return new Archive($archiveData, array( 'client' => $this->client ));
}
/**
* Gets an Archive object for the given archive ID.
*
* @param String $archiveId The archive ID.
*
* @throws ArchiveException There is no archive with the specified ID.
* @throws InvalidArgumentException The archive ID provided is null or an empty string.
*
* @return Archive The Archive object.
*/
public function getArchive($archiveId)
{
Validators::validateArchiveId($archiveId);
$archiveData = $this->client->getArchive($archiveId);
return new Archive($archiveData, array( 'client' => $this->client ));
}
/**
* Deletes an OpenTok archive.
* <p>
* You can only delete an archive which has a status of "available", "uploaded", or "deleted".
* Deleting an archive removes its record from the list of archives. For an "available" archive,
* it also removes the archive file, making it unavailable for download. For a "deleted"
* archive, the archive remains deleted.
*
* @param String $archiveId The archive ID of the archive you want to delete.
*
* @return Boolean Returns true on success.
*
* @throws ArchiveException There archive status is not "available", "updated",
* or "deleted".
*/
public function deleteArchive($archiveId)
{
Validators::validateArchiveId($archiveId);
return $this->client->deleteArchive($archiveId);
}
/**
* Returns a list of archives for a session.
*
* The <code>items()</code> method of this object returns a list of
* archives that are completed and in-progress, for your API key.
*
* @param integer $offset Optional. The index offset of the first archive. 0 is offset of the
* most recently started archive. 1 is the offset of the archive that started prior to the most
* recent archive. If you do not specify an offset, 0 is used.
* @param integer $count Optional. The number of archives to be returned. The maximum number of
* archives returned is 1000.
* @param string $sessionId Optional. The OpenTok session Id for which you want to retrieve Archives for. If no session Id
* is specified, the method will return archives from all sessions created with the API key.
*
* @return ArchiveList An ArchiveList object. Call the items() method of the ArchiveList object
* to return an array of Archive objects.
*/
public function listArchives($offset = 0, $count = null, $sessionId = null)
{
// validate params
Validators::validateOffsetAndCount($offset, $count);
if (!is_null($sessionId)) {
Validators::validateSessionIdBelongsToKey($sessionId, $this->apiKey);
}
$archiveListData = $this->client->listArchives($offset, $count, $sessionId);
return new ArchiveList($archiveListData, array( 'client' => $this->client ));
}
/**
* Updates the stream layout in an OpenTok Archive.
*/
public function setArchiveLayout(string $archiveId, Layout $layoutType): void
{
Validators::validateArchiveId($archiveId);
$this->client->setArchiveLayout($archiveId, $layoutType);
}
/**
* Sets the layout class list for streams in a session.
*
* Layout classes are used in
* the layout for composed archives and live streaming broadcasts. For more information, see
* <a href="https://tokbox.com/developer/guides/archiving/layout-control.html">Customizing
* the video layout for composed archives</a> and
* <a href="https://tokbox.com/developer/guides/broadcast/live-streaming/#configuring-video-layout-for-opentok-live-streaming-broadcasts">Configuring
* video layout for OpenTok live streaming broadcasts</a>.
* @param string $sessionId The session ID of the session the streams belong to.
*
* @param array $classListArray The connectionId of the connection in a session.
*/
public function setStreamClassLists($sessionId, $classListArray = array())
{
Validators::validateSessionIdBelongsToKey($sessionId, $this->apiKey);
foreach ($classListArray as $item) {
Validators::validateLayoutClassListItem($item);
}
$this->client->setStreamClassLists($sessionId, $classListArray);
}
/**
* Disconnects a specific client from an OpenTok session.
*
* @param string $sessionId The OpenTok session ID that the client is connected to.
*
* @param string $connectionId The connection ID of the connection in the session.
*/
public function forceDisconnect($sessionId, $connectionId)
{
Validators::validateSessionIdBelongsToKey($sessionId, $this->apiKey);
Validators::validateConnectionId($connectionId);
return $this->client->forceDisconnect($sessionId, $connectionId);
}
/**
* Force the publisher of a specific stream to mute its published audio.
*
* <p>
* Also see the
* <a href="classes/OpenTok-OpenTok.html#method_forceMuteAll">OpenTok->forceMuteAll()</a>
* method.
*
* @param string $sessionId The OpenTok session ID containing the stream.
*
* @param string $streamId The stream ID.
*
* @return bool Whether the call succeeded or failed.
*/
public function forceMuteStream(string $sessionId, string $streamId): bool
{
Validators::validateSessionId($sessionId);
Validators::validateStreamId($streamId);
try {
$this->client->forceMuteStream($sessionId, $streamId);
} catch (\Exception $e) {
return false;
}
return true;
}
/**
* Force all streams (except for an optional list of streams) in an OpenTok session
* to mute published audio.
*
* <p>
* In addition to existing streams, any streams that are published after the call to
* this method are published with audio muted. You can remove the mute state of a session
* <a href="classes/OpenTok-OpenTok.html#method_disableForceMute">OpenTok->disableForceMute()</a>
* method.
* <p>
* Also see the
* <a href="classes/OpenTok-OpenTok.html#method_forceMuteStream">OpenTok->forceMuteStream()</a>
* method.
*
* @param string $sessionId The OpenTok session ID.
*
* @param array<string> $options This array defines options and includes the following keys:
*
* <ul>
* <li><code>'excludedStreams'</code> (array, optional) — An array of stream IDs
* corresponding to streams that should not be muted. This is an optional property.
* If you omit this property, all streams in the session will be muted.</li>
* </ul>
*
* @return bool Whether the call succeeded or failed.
*/
public function forceMuteAll(string $sessionId, array $options): bool
{
// Active is always true when forcing mute all
$options['active'] = true;
Validators::validateSessionId($sessionId);
Validators::validateForceMuteAllOptions($options);
try {
$this->client->forceMuteAll($sessionId, $options);
} catch (\Exception $e) {
return false;
}
return true;
}
/**
* Disables the active mute state of the session. After you call this method, new streams
* published to the session will no longer have audio muted.
*
* <p>
* After you call the
* <a href="classes/OpenTok-OpenTok.html#method_forceMuteAll">OpenTok->forceMuteAll()</a> method
* any streams published after the call are published with audio muted. Call the
* <c>disableForceMute()</c> method to remove the mute state of a session, so that
* new published streams are not automatically muted.
*
* @param string $sessionId The OpenTok session ID.
*
* @param array<string> $options This array defines options and includes the following keys:
*
* <ul>
* <li><code>'excludedStreams'</code> (array, optional) — An array of stream IDs
* corresponding to streams that should not be muted. This is an optional property.
* If you omit this property, all streams in the session will be muted.</li>
* </ul>
*
* @return bool Whether the call succeeded or failed.
*/
public function disableForceMute(string $sessionId, array $options): bool
{
// Active is always false when disabling force mute
$options['active'] = false;
Validators::validateSessionId($sessionId);
Validators::validateForceMuteAllOptions($options);
try {
$this->client->forceMuteAll($sessionId, $options);
} catch (\Exception $e) {
return false;
}
return true;
}
/**
* Starts a live streaming broadcast of an OpenTok session.
*
* @param String $sessionId The session ID of the session to be broadcast.
*
* @param array $options (Optional) An array with options for the broadcast. This array has
* the following properties:
*
* <ul>
* <li><code>layout</code> (Layout) — (Optional) An object defining the initial
* layout type of the broadcast. If you do not specify an initial layout type,
* the broadcast stream uses the Best Fit layout type. For more information, see
* <a href="https://tokbox.com/developer/guides/broadcast/live-streaming/#configuring-live-streaming-video-layout">Configuring
* Video Layout for the OpenTok live streaming feature</a>.
* </li>
*
* <li><code>streamMode</code> (String) — Whether streams included in the broadcast
* are selected automatically (<code>StreamMode.AUTO</code>, the default) or manually
* (<code>StreamMode.MANUAL</code>). When streams are selected automatically
* (<code>StreamMode.AUTO</code>), all streams in the session can be included in the broadcast.
* When streams are selected manually (<code>StreamMode.MANUAL</code>), you specify streams
* to be included based on calls to the <code>Broadcast.addStreamToBroadcast()</code> and
* <code>Broadcast.removeStreamFromBroadcast()</code> methods. With manual mode, you can specify
* whether a stream's audio, video, or both are included in the broadcast. In both automatic and
* manual modes, the broadcast composer includes streams based on
* <a href="https://tokbox.com/developer/guides/archive-broadcast-layout/#stream-prioritization-rules">stream
* prioritization rules</a>.</li>
*
* <li><code>multiBroadcastTag</code> (String) (Optional) — Set this to support multiple broadcasts for
* the same session simultaneously. Set this to a unique string for each simultaneous broadcast of an ongoing session.
* Note that the `multiBroadcastTag` value is *not* included in the response for the methods to
* {https://tokbox.com/developer/rest/#list_broadcasts list live streaming broadcasts} and
* {https://tokbox.com/developer/rest/#get_info_broadcast get information about a live streaming broadcast}.
* {https://tokbox.com/developer/guides/broadcast/live-streaming#simultaneous-broadcasts See Simultaneous broadcasts}.</li>
*
* <li><code>resolution</code> — The resolution of the broadcast: either "640x480" (SD landscape, the default), "1280x720" (HD landscape),
* "1920x1080" (FHD landscape), "480x640" (SD portrait), "720x1280" (HD portrait), or "1080x1920"
* (FHD portrait).</li>
*
* <li><code>maxBitRate</code> — Max Bitrate allowed for the broadcast composing. Must be between
* 400000 and 2000000.</li>
*
* <li><code>outputs</code> (Array) —
* Defines the HLS broadcast and RTMP streams. You can provide the following keys:
* <ul>
* <li><code>hls</code> (Array) — available with the following options:
* <p>
* <ul>
* <li><code>'dvr'</code> (Bool) — Whether to enable
* <a href="https://tokbox.com/developer/guides/broadcast/live-streaming/#dvr">DVR functionality</a>
* — rewinding, pausing, and resuming — in players that support it (<code>true</code>),
* or not (<code>false</code>, the default). With DVR enabled, the HLS URL will include
* a ?DVR query string appended to the end.
* </li>
* <li><code>'lowLatency'</code> (Bool) — Whether to enable
* <a href="https://tokbox.com/developer/guides/broadcast/live-streaming/#low-latency">low-latency mode</a>
* for the HLS stream. Some HLS players do not support low-latency mode. This feature
* is incompatible with DVR mode HLS broadcasts.
* </li>
* </ul>
* </p>
* </li>
* <li><code>rtmp</code> (Array) — An array of arrays defining RTMP streams to broadcast. You
* can specify up to five target RTMP streams. Each RTMP stream array has the following keys:
* <ul>
* <li><code>id</code></code> (String) — The stream ID (optional)</li>
* <li><code>serverUrl</code> (String) — The RTMP server URL</li>
* <li><code>streamName</code> (String) — The stream name, such as
* the YouTube Live stream name or the Facebook stream key</li>
* </ul>
* </li>
* </ul>
* </ul>
*
* @return Broadcast An object with properties defining the broadcast.
*/
public function startBroadcast(string $sessionId, array $options = []): Broadcast
{
// unpack optional arguments (merging with default values) into named variables
// NOTE: although the server can be authoritative about the default value of layout, its
// not preferred to depend on that in the SDK because its then harder to garauntee backwards
// compatibility
if (isset($options['maxBitRate'])) {
Validators::validateBroadcastBitrate($options['maxBitRate']);
}
if (isset($options['resolution'])) {
Validators::validateResolution($options['resolution']);
}
if (isset($options['outputs']['hls'])) {
Validators::validateBroadcastOutputOptions($options['outputs']['hls']);
}
if (isset($options['outputs']['rtmp'])) {
Validators::validateRtmpStreams($options['outputs']['rtmp']);
}
$defaults = [
'layout' => Layout::getBestFit(),
'hasAudio' => true,
'hasVideo' => true,
'streamMode' => 'auto',
'resolution' => '640x480',
'maxBitRate' => 2000000,
'outputs' => [
'hls' => [
'dvr' => false,
'lowLatency' => false
]
]
];
$options = array_merge($defaults, $options);
Validators::validateSessionId($sessionId);
Validators::validateLayout($options['layout']);
Validators::validateHasStreamMode($options['streamMode']);
$broadcastData = $this->client->startBroadcast($sessionId, $options);
return new Broadcast($broadcastData, ['client' => $this->client]);
}
/**
* Stops a broadcast.
*
* @param String $broadcastId The ID of the broadcast.
*/
public function stopBroadcast($broadcastId): Broadcast
{
// validate arguments
Validators::validateBroadcastId($broadcastId);
// make API call
$broadcastData = $this->client->stopBroadcast($broadcastId);
return new Broadcast($broadcastData, array(
'client' => $this->client,
'isStopped' => true
));
}
/**
* Gets information about an OpenTok broadcast.
*
* @param String $broadcastId The ID of the broadcast.
*
* @return Broadcast An object with properties defining the broadcast.
*/
public function getBroadcast($broadcastId): Broadcast
{
Validators::validateBroadcastId($broadcastId);