Passed
Push — master ( f5e35b...7b483a )
by Jacobo
07:40 queued 04:57
created

OpenVidu::sendSignal()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 17
nc 5
nop 1
dl 0
loc 20
rs 9.3888
c 0
b 0
f 0
1
<?php
2
3
namespace SquareetLabs\LaravelOpenVidu;
4
5
use Exception;
6
use GuzzleHttp\Client;
7
use GuzzleHttp\RequestOptions;
8
use Illuminate\Support\Facades\Cache;
9
use Psr\SimpleCache\InvalidArgumentException;
10
use SquareetLabs\LaravelOpenVidu\Builders\RecordingBuilder;
11
use SquareetLabs\LaravelOpenVidu\Enums\Uri;
12
use SquareetLabs\LaravelOpenVidu\Exceptions\OpenViduException;
13
use SquareetLabs\LaravelOpenVidu\Exceptions\OpenViduProblemWithBodyParameterException;
14
use SquareetLabs\LaravelOpenVidu\Exceptions\OpenViduRecordingNotFoundException;
15
use SquareetLabs\LaravelOpenVidu\Exceptions\OpenViduRecordingResolutionException;
16
use SquareetLabs\LaravelOpenVidu\Exceptions\OpenViduRecordingStatusException;
17
use SquareetLabs\LaravelOpenVidu\Exceptions\OpenViduServerRecordingIsDisabledException;
18
use SquareetLabs\LaravelOpenVidu\Exceptions\OpenViduSessionCantRecordingException;
19
use SquareetLabs\LaravelOpenVidu\Exceptions\OpenViduSessionHasNotConnectedParticipantsException;
20
use SquareetLabs\LaravelOpenVidu\Exceptions\OpenViduSessionNotFoundException;
21
22
/**
23
 * Class OpenVidu
24
 * @package App\SquareetLabs\LaravelOpenVidu
25
 */
26
class OpenVidu
27
{
28
    /**
29
     * @var Client
30
     */
31
    private $client;
32
33
    /**
34
     * @var
35
     */
36
    private $config;
37
38
39
    /**
40
     * SmsUp constructor.
41
     * @param  array  $config
42
     */
43
    public function __construct(array $config)
44
    {
45
        $this->config = $config;
46
    }
47
48
    /**
49
     * @param  SessionProperties|null  $properties
50
     * @return Session
51
     * @throws Exceptions\OpenViduException
52
     */
53
    public function createSession(?SessionProperties $properties = null): Session
54
    {
55
        $session = new Session($this->client(), $properties);
56
        Cache::store('openvidu')->forever($session->getSessionId(), $session->toJson());
57
        return $session;
58
    }
59
60
    /**
61
     * @param Client $client
62
     */
63
    public function setClient(Client $client)
64
    {
65
        $this->client = $client;
66
    }
67
68
    /**
69
     * @return Client
70
     */
71
    private function client(): Client
72
    {
73
        if($this->client){
74
            return $this->client;
75
        }
76
77
        $client = new Client([
78
            'headers' => [
79
                'Content-Type' => 'application/json',
80
                'Accept' => 'application/json',
81
            ],
82
            'auth' => [
83
                $this->config['app'], $this->config['secret']
84
            ],
85
            'base_uri' => $this->config['domain'].':'.$this->config['port'],
86
            'debug' => $this->config['debug'],
87
            'http_errors' => false,
88
            'verify' => false
89
        ]);
90
        return $client;
91
    }
92
93
    /**
94
     * Starts the recording of a {@see Session}
95
     * @param  RecordingProperties  $properties
96
     * @return Recording
97
     * @throws OpenViduException
98
     * @throws OpenViduRecordingResolutionException
99
     * @throws OpenViduServerRecordingIsDisabledException
100
     * @throws OpenViduSessionCantRecordingException
101
     * @throws OpenViduSessionHasNotConnectedParticipantsException
102
     * @throws OpenViduSessionNotFoundException
103
     * @throws InvalidArgumentException
104
     * @throws Exceptions\OpenViduInvalidArgumentException
105
     */
106
    public function startRecording(RecordingProperties $properties): Recording
107
    {
108
        $activeSession = $this->getSession($properties->session());
109
        if ($activeSession->isBeingRecorded()) {
110
            $lastRecordingId = $activeSession->getLastRecordingId();
111
            if (!$lastRecordingId) {
112
                throw new OpenViduSessionCantRecordingException("The session is not configured for using media routed or has recording problems");
113
            }
114
            return $this->getRecording($lastRecordingId);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getRecording($lastRecordingId) returns the type string which is incompatible with the type-hinted return SquareetLabs\LaravelOpenVidu\Recording.
Loading history...
115
        }
116
        $response = $this->client()->post(Uri::RECORDINGS_START, [
117
            RequestOptions::JSON => $properties->toArray() ?? null
118
        ]);
119
        switch ($response->getStatusCode()) {
120
            case 200:
121
                $recording = RecordingBuilder::build(json_decode($response->getBody()->getContents(), true));
122
                
123
                if ($activeSession != null) {
124
                    $activeSession->setIsBeingRecorded(true);
125
                    $activeSession->setLastRecordingId($recording->id);
0 ignored issues
show
Bug introduced by
The property id is declared private in SquareetLabs\LaravelOpenVidu\Recording and cannot be accessed from this context.
Loading history...
126
                }
127
                return $recording;
128
            case 404:
129
                throw new OpenViduSessionNotFoundException();
130
                break;
131
            case 406:
132
                throw new OpenViduSessionHasNotConnectedParticipantsException();
133
                break;
134
            case 409:
135
                throw new OpenViduSessionCantRecordingException("The session is not configured for using media routed or it is already being recorded");
136
                break;
137
            case 422:
138
                throw new OpenViduRecordingResolutionException();
139
                break;
140
            case 501:
141
                throw new OpenViduServerRecordingIsDisabledException();
142
                break;
143
            default:
144
                throw new OpenViduException("Invalid response status code ".$response->getStatusCode(), $response->getStatusCode());
145
        }
146
    }
147
148
    /**
149
     * Gets an existing {@see Session}
150
     * @param  string  $sessionId
151
     * @return Session
152
     * @throws OpenViduException
153
     * @throws OpenViduSessionNotFoundException
154
     * @throws InvalidArgumentException
155
     */
156
    public function getSession(string $sessionId): Session
157
    {
158
        if (Cache::store('openvidu')->has($sessionId)) {
159
            return (new Session($this->client()))->fromJson(Cache::store('openvidu')->get($sessionId));
160
        }
161
        throw new OpenViduSessionNotFoundException();
162
    }
163
164
165
    /**
166
     * Check if exists {@see Session}
167
     * @param  string  $sessionId
168
     * @return bool
169
     * @throws InvalidArgumentException
170
     */
171
    public function existsSession(string $sessionId): bool
172
    {
173
        return Cache::store('openvidu')->has($sessionId);
174
    }
175
176
    /**
177
     * Stops the recording of a {@see Session}
178
     * @param  string  $recordingId  The `id` property of the {@see Recording} you want to stop
179
     * @return Recording
180
     * @throws OpenViduException
181
     * @throws OpenViduRecordingNotFoundException
182
     * @throws OpenViduRecordingStatusException
183
     * @throws OpenViduSessionNotFoundException
184
     * @throws InvalidArgumentException
185
     * @throws Exceptions\OpenViduInvalidArgumentException
186
     */
187
    public function stopRecording(string $recordingId): Recording
188
    {        
189
        $response = $this->client()->post(Uri::RECORDINGS_STOP.'/'.$recordingId);
190
        switch ($response->getStatusCode()) {
191
            case 200:
192
                $recording = RecordingBuilder::build(json_decode($response->getBody()->getContents(), true));
193
                $activeSession = $this->getSession($recording->getSessionId());
194
                if ($activeSession != null) {
195
                    $activeSession->setIsBeingRecorded(false);
196
                    $activeSession->setLastRecordingId(null);
0 ignored issues
show
Bug introduced by
null of type null is incompatible with the type string expected by parameter $lastRecordingId of SquareetLabs\LaravelOpen...n::setLastRecordingId(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

196
                    $activeSession->setLastRecordingId(/** @scrutinizer ignore-type */ null);
Loading history...
197
                }
198
                return $recording;
199
            case 404:
200
                throw new OpenViduRecordingNotFoundException();
201
                break;
202
            case 406:
203
                throw new OpenViduRecordingStatusException("The recording has `starting` status. Wait until `started` status before stopping the recording.");
204
                break;
205
            default:
206
                throw new OpenViduException("Invalid response status code ".$response->getStatusCode(), $response->getStatusCode());
207
        }
208
    }
209
210
    /**
211
     * Gets an existing {@see Recording}
212
     * @param  string  $recordingId  The `id` property of the {@see Recording} you want to retrieve
213
     * @return string
214
     * @throws OpenViduException
215
     * @throws OpenViduRecordingNotFoundException
216
     * @throws Exceptions\OpenViduInvalidArgumentException
217
     */
218
    public function getRecording(string $recordingId)
219
    {
220
        $response = $this->client()->get(Uri::RECORDINGS_URI.'/'.$recordingId);
221
        switch ($response->getStatusCode()) {
222
            case 200:
223
                $recording = RecordingBuilder::build(json_decode($response->getBody()->getContents(), true));
224
                return $recording;
225
            case 404:
226
                throw new OpenViduRecordingNotFoundException();
227
                break;
228
            default:
229
                throw new OpenViduException("Invalid response status code ".$response->getStatusCode(), $response->getStatusCode());
230
        }
231
    }
232
233
    /**
234
     * Gets an array with all existing recordings
235
     * @return array
236
     * @throws OpenViduException
237
     * @throws Exceptions\OpenViduInvalidArgumentException
238
     */
239
    public function getRecordings(): array
240
    {
241
        $recordings = [];
242
        $response = $this->client()->get(Uri::RECORDINGS_URI);
243
        switch ($response->getStatusCode()) {
244
            case 200:
245
                $items = json_decode($response->getBody()->getContents(), true);
246
                foreach ($items as $item) {
247
                    $recordings[] = RecordingBuilder::build($item);
248
                }
249
                return $recordings;
250
            default:
251
                throw new OpenViduException("Invalid response status code ".$response->getStatusCode(), $response->getStatusCode());
252
        }
253
    }
254
255
256
    /**
257
     * Deletes a {@see Recording}. The recording must have status `stopped`, `ready` or `failed`
258
     * @param  string  $recordingId  The `id` property of the {@see Recording} you want to delete
259
     * @return bool
260
     * @throws OpenViduException
261
     * @throws OpenViduRecordingNotFoundException
262
     * @throws OpenViduRecordingStatusException
263
     */
264
    public function deleteRecording(string $recordingId): bool
265
    {
266
        $response = $this->client()->delete(Uri::RECORDINGS_URI.'/'.$recordingId);
267
268
        switch ($response->getStatusCode()) {
269
            case 200:
270
                return true;
271
            case 404:
272
                throw new OpenViduRecordingNotFoundException();
273
                break;
274
            case 409:
275
                throw new OpenViduRecordingStatusException("The recording has `started` status. Stop it before deletion.");
276
                break;
277
            default:
278
                throw new OpenViduException("Invalid response status code ".$response->getStatusCode(), $response->getStatusCode());
279
        }
280
    }
281
282
    /**
283
     * Returns the list of active sessions. <strong>This value will remain unchanged
284
     * since the last time method {@link SquareetLabs\LaravelOpenVidu#fetch()}
285
     * was called</strong>. Exceptions to this rule are:
286
     * <ul>
287
     * <li>Calling {@see Session::fetch} updates that
288
     * specific Session status</li>
289
     * <li>Calling {@see Session::close()} automatically
290
     * removes the Session from the list of active Sessions</li>
291
     * <li>Calling
292
     * {@see Session::forceDisconnect(string)}
293
     * automatically updates the inner affected connections for that specific
294
     * Session</li>
295
     * <li>Calling {@see Session::forceUnpublish(string)}
296
     * also automatically updates the inner affected connections for that specific
297
     * Session</li>
298
     * <li>Calling {@see OpenVidu::startRecording(string)}
299
     * and {@see LaravelOpenVidu::stopRecording(string)}
300
     * automatically updates the recording status of the Session
301
     * </ul>
302
     * <br>
303
     * To get the list of active sessions with their current actual value, you must
304
     * call first {@see OpenVidu::fetch()} and then
305
     * {@see OpenVidu::getActiveSessions()}
306
     * @throws OpenViduException
307
     */
308
    public function getActiveSessions(): array
309
    {
310
        try {
311
            return Cache::store('openvidu')->getAll();
312
        } catch (Exception $e) {
313
            throw new OpenViduException("Make sure you have correctly configured the openvidu cache driver.", 500);
314
        }
315
    }
316
317
    /**
318
     * Sends signal to session with given SignalProperties
319
     * @param SignalProperties $properties
320
     * @return bool
321
     * @throws OpenViduException
322
     * @throws OpenViduProblemWithBodyParameterException
323
     * @throws OpenViduSessionHasNotConnectedParticipantsException
324
     * @throws OpenViduSessionNotFoundException
325
     */
326
    public function sendSignal(SignalProperties $properties): bool
327
    {
328
        $activeSession = $this->getSession($properties->session());
0 ignored issues
show
Unused Code introduced by
The assignment to $activeSession is dead and can be removed.
Loading history...
329
        $response = $this->client()->post(Uri::SIGNAL_URI, [
330
            RequestOptions::JSON => $properties->toArray() ?? null
331
        ]);
332
        switch ($response->getStatusCode()) {
333
            case 200:
334
                return true;
335
            case 400:
336
                throw new OpenViduProblemWithBodyParameterException();
337
                break;
338
            case 404:
339
                throw new OpenViduSessionNotFoundException();
340
                break;
341
            case 406:
342
                throw new OpenViduSessionHasNotConnectedParticipantsException();
343
                break;
344
            default:
345
                throw new OpenViduException("Invalid response status code " . $response->getStatusCode(), $response->getStatusCode());
346
        }
347
    }
348
}
349
350