Passed
Push — master ( c00b75...febabf )
by Jacobo
01:08 queued 11s
created

OpenVidu::setClient()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 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
     * @var
34
     */
35
    private $config;
36
37
38
    /**
39
     * SmsUp constructor.
40
     * @param  array  $config
41
     */
42
    public function __construct(array $config)
43
    {
44
        $this->config = $config;
45
    }
46
47
    /**
48
     * @param  SessionProperties|null  $properties
49
     * @return Session
50
     * @throws Exceptions\OpenViduException
51
     */
52
    public function createSession(?SessionProperties $properties = null): Session
53
    {
54
        $session = new Session($this->client(), $properties);
55
        Cache::store('openvidu')->forever($session->getSessionId(), $session->toJson());
56
        return $session;
57
    }
58
59
    /**
60
     * @param Client $client
61
     */
62
    public function setClient(Client $client)
63
    {
64
        $this->client = $client;
65
    }
66
67
    /**
68
     * @return Client
69
     */
70
    private function client(): Client
71
    {
72
        if($this->client){
73
            return $this->client;
74
        }
75
76
        $client = new Client([
77
            'headers' => [
78
                'Content-Type' => 'application/json',
79
                'Accept' => 'application/json',
80
            ],
81
            'auth' => [
82
                $this->config['app'], $this->config['secret']
83
            ],
84
            'base_uri' => $this->config['domain'].':'.$this->config['port'],
85
            'debug' => $this->config['debug'],
86
            'http_errors' => false,
87
            'verify' => false
88
        ]);
89
        return $client;
90
    }
91
92
    /**
93
     * Starts the recording of a {@see Session}
94
     * @param  RecordingProperties  $properties
95
     * @return Recording
96
     * @throws OpenViduException
97
     * @throws OpenViduRecordingResolutionException
98
     * @throws OpenViduServerRecordingIsDisabledException
99
     * @throws OpenViduSessionCantRecordingException
100
     * @throws OpenViduSessionHasNotConnectedParticipantsException
101
     * @throws OpenViduSessionNotFoundException
102
     * @throws InvalidArgumentException
103
     * @throws Exceptions\OpenViduInvalidArgumentException
104
     */
105
    public function startRecording(RecordingProperties $properties): Recording
106
    {
107
        $activeSession = $this->getSession($properties->session());
108
        if ($activeSession->isBeingRecorded()) {
109
            $lastRecordingId = $activeSession->getLastRecordingId();
110
            if (!$lastRecordingId) {
111
                throw new OpenViduSessionCantRecordingException("The session is not configured for using media routed or has recording problems");
112
            }
113
            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...
114
        }
115
        $response = $this->client()->post(Uri::RECORDINGS_START, [
116
            RequestOptions::JSON => $properties->toArray() ?? null
117
        ]);
118
        switch ($response->getStatusCode()) {
119
            case 200:
120
                $recording = RecordingBuilder::build(json_decode($response->getBody()->getContents(), true));
121
                
122
                if ($activeSession != null) {
123
                    $activeSession->setIsBeingRecorded(true);
124
                    $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...
125
                }
126
                return $recording;
127
            case 404:
128
                throw new OpenViduSessionNotFoundException();
129
                break;
130
            case 406:
131
                throw new OpenViduSessionHasNotConnectedParticipantsException();
132
                break;
133
            case 409:
134
                throw new OpenViduSessionCantRecordingException("The session is not configured for using media routed or it is already being recorded");
135
                break;
136
            case 422:
137
                throw new OpenViduRecordingResolutionException();
138
                break;
139
            case 501:
140
                throw new OpenViduServerRecordingIsDisabledException();
141
                break;
142
            default:
143
                throw new OpenViduException("Invalid response status code ".$response->getStatusCode(), $response->getStatusCode());
144
        }
145
    }
146
147
    /**
148
     * Gets an existing {@see Session}
149
     * @param  string  $sessionId
150
     * @return Session
151
     * @throws OpenViduException
152
     * @throws OpenViduSessionNotFoundException
153
     * @throws InvalidArgumentException
154
     */
155
    public function getSession(string $sessionId): Session
156
    {
157
        if (Cache::store('openvidu')->has($sessionId)) {
158
            return (new Session($this->client()))->fromJson(Cache::store('openvidu')->get($sessionId));
159
        }
160
        throw new OpenViduSessionNotFoundException();
161
    }
162
163
164
    /**
165
     * Check if exists {@see Session}
166
     * @param  string  $sessionId
167
     * @return bool
168
     * @throws InvalidArgumentException
169
     */
170
    public function existsSession(string $sessionId): bool
171
    {
172
        return Cache::store('openvidu')->has($sessionId);
173
    }
174
175
    /**
176
     * Stops the recording of a {@see Session}
177
     * @param  string  $recordingId  The `id` property of the {@see Recording} you want to stop
178
     * @return Recording
179
     * @throws OpenViduException
180
     * @throws OpenViduRecordingNotFoundException
181
     * @throws OpenViduRecordingStatusException
182
     * @throws OpenViduSessionNotFoundException
183
     * @throws InvalidArgumentException
184
     * @throws Exceptions\OpenViduInvalidArgumentException
185
     */
186
    public function stopRecording(string $recordingId): Recording
187
    {        
188
        $response = $this->client()->post(Uri::RECORDINGS_STOP.'/'.$recordingId);
189
        switch ($response->getStatusCode()) {
190
            case 200:
191
                $recording = RecordingBuilder::build(json_decode($response->getBody()->getContents(), true));
192
                $activeSession = $this->getSession($recording->getSessionId());
193
                if ($activeSession != null) {
194
                    $activeSession->setIsBeingRecorded(false);
195
                    $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

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