Passed
Pull Request — master (#5)
by
unknown
02:49
created

OpenVidu   A

Complexity

Total Complexity 35

Size/Duplication

Total Lines 291
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 111
c 2
b 0
f 0
dl 0
loc 291
rs 9.6
wmc 35

12 Methods

Rating   Name   Duplication   Size   Complexity  
A getActiveSessions() 0 6 2
A getRecording() 0 12 3
A setClient() 0 4 1
A __construct() 0 3 1
A client() 0 20 2
A stopRecording() 0 20 5
A getRecordings() 0 13 3
A getSession() 0 6 2
A deleteRecording() 0 15 4
A existsSession() 0 3 1
A createSession() 0 5 1
B startRecording() 0 39 10
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\OpenViduRecordingNotFoundException;
14
use SquareetLabs\LaravelOpenVidu\Exceptions\OpenViduRecordingResolutionException;
15
use SquareetLabs\LaravelOpenVidu\Exceptions\OpenViduRecordingStatusException;
16
use SquareetLabs\LaravelOpenVidu\Exceptions\OpenViduServerRecordingIsDisabledException;
17
use SquareetLabs\LaravelOpenVidu\Exceptions\OpenViduSessionCantRecordingException;
18
use SquareetLabs\LaravelOpenVidu\Exceptions\OpenViduSessionHasNotConnectedParticipantsException;
19
use SquareetLabs\LaravelOpenVidu\Exceptions\OpenViduSessionNotFoundException;
20
21
/**
22
 * Class OpenVidu
23
 * @package App\SquareetLabs\LaravelOpenVidu
24
 */
25
class OpenVidu
26
{
27
    /**
28
     * @var Client
29
     */
30
    private $client;
31
    
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
     * @return OpenVidu
63
     */
64
    public function setClient(Client $client)
65
    {
66
        $this->client = $client;
67
        return $this;
68
    }
69
70
    /**
71
     * @return Client
72
     */
73
    private function client(): Client
74
    {
75
        if($this->client){
76
            return $this->client;
77
        }
78
        
79
        $client = new Client([
80
            'headers' => [
81
                'Content-Type' => 'application/json',
82
                'Accept' => 'application/json',
83
            ],
84
            'auth' => [
85
                $this->config['app'], $this->config['secret']
86
            ],
87
            'base_uri' => $this->config['domain'].':'.$this->config['port'],
88
            'debug' => $this->config['debug'],
89
            'http_errors' => false,
90
            'verify' => false
91
        ]);
92
        return $client;
93
    }
94
95
    /**
96
     * Starts the recording of a {@see Session}
97
     * @param  RecordingProperties  $properties
98
     * @return Recording
99
     * @throws OpenViduException
100
     * @throws OpenViduRecordingResolutionException
101
     * @throws OpenViduServerRecordingIsDisabledException
102
     * @throws OpenViduSessionCantRecordingException
103
     * @throws OpenViduSessionHasNotConnectedParticipantsException
104
     * @throws OpenViduSessionNotFoundException
105
     * @throws InvalidArgumentException
106
     * @throws Exceptions\OpenViduInvalidArgumentException
107
     */
108
    public function startRecording(RecordingProperties $properties): Recording
109
    {
110
        $activeSession = $this->getSession($properties->session());
111
        if ($activeSession->isBeingRecorded()) {
112
            $lastRecordingId = $activeSession->getLastRecordingId();
113
            if (!$lastRecordingId) {
114
                throw new OpenViduSessionCantRecordingException("The session is not configured for using media routed or has recording problems");
115
            }
116
            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...
117
        }
118
        $response = $this->client()->post(Uri::RECORDINGS_START, [
119
            RequestOptions::JSON => $properties->toArray() ?? null
120
        ]);
121
        switch ($response->getStatusCode()) {
122
            case 200:
123
                $recording = RecordingBuilder::build(json_decode($response->getBody()->getContents(), true));
124
                
125
                if ($activeSession != null) {
126
                    $activeSession->setIsBeingRecorded(true);
127
                    $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...
128
                }
129
                return $recording;
130
            case 404:
131
                throw new OpenViduSessionNotFoundException();
132
                break;
133
            case 406:
134
                throw new OpenViduSessionHasNotConnectedParticipantsException();
135
                break;
136
            case 409:
137
                throw new OpenViduSessionCantRecordingException("The session is not configured for using media routed or it is already being recorded");
138
                break;
139
            case 422:
140
                throw new OpenViduRecordingResolutionException();
141
                break;
142
            case 501:
143
                throw new OpenViduServerRecordingIsDisabledException();
144
                break;
145
            default:
146
                throw new OpenViduException("Invalid response status code ".$response->getStatusCode(), $response->getStatusCode());
147
        }
148
    }
149
150
    /**
151
     * Gets an existing {@see Session}
152
     * @param  string  $sessionId
153
     * @return Session
154
     * @throws OpenViduException
155
     * @throws OpenViduSessionNotFoundException
156
     * @throws InvalidArgumentException
157
     */
158
    public function getSession(string $sessionId): Session
159
    {
160
        if (Cache::store('openvidu')->has($sessionId)) {
161
            return (new Session($this->client()))->fromJson(Cache::store('openvidu')->get($sessionId));
162
        }
163
        throw new OpenViduSessionNotFoundException();
164
    }
165
166
167
    /**
168
     * Check if exists {@see Session}
169
     * @param  string  $sessionId
170
     * @return bool
171
     * @throws InvalidArgumentException
172
     */
173
    public function existsSession(string $sessionId): bool
174
    {
175
        return Cache::store('openvidu')->has($sessionId);
176
    }
177
178
    /**
179
     * Stops the recording of a {@see Session}
180
     * @param  string  $recordingId  The `id` property of the {@see Recording} you want to stop
181
     * @return Recording
182
     * @throws OpenViduException
183
     * @throws OpenViduRecordingNotFoundException
184
     * @throws OpenViduRecordingStatusException
185
     * @throws OpenViduSessionNotFoundException
186
     * @throws InvalidArgumentException
187
     * @throws Exceptions\OpenViduInvalidArgumentException
188
     */
189
    public function stopRecording(string $recordingId): Recording
190
    {        
191
        $response = $this->client()->post(Uri::RECORDINGS_STOP.'/'.$recordingId);
192
        switch ($response->getStatusCode()) {
193
            case 200:
194
                $recording = RecordingBuilder::build(json_decode($response->getBody()->getContents(), true));
195
                $activeSession = $this->getSession($recording->getSessionId());
196
                if ($activeSession != null) {
197
                    $activeSession->setIsBeingRecorded(false);
198
                    $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

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