Passed
Push — master ( 2e8699...aacee4 )
by Jacobo
04:45
created

OpenVidu::existsSession()   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
    /**
29
     * @var
30
     */
31
    private $config;
32
33
34
    /**
35
     * SmsUp constructor.
36
     * @param  array  $config
37
     */
38
    public function __construct(array $config)
39
    {
40
        $this->config = $config;
41
    }
42
43
    /**
44
     * @param  SessionProperties|null  $properties
45
     * @return Session
46
     * @throws Exceptions\OpenViduException
47
     */
48
    public function createSession(?SessionProperties $properties = null): Session
49
    {
50
        $session = new Session($this->client(), $properties);
51
        Cache::store('openvidu')->forever($session->getSessionId(), $session->toJson());
52
        return $session;
53
    }
54
55
    /**
56
     * @return Client
57
     */
58
    private function client(): Client
59
    {
60
        $client = new Client([
61
            'headers' => [
62
                'Content-Type' => 'application/json',
63
                'Accept' => 'application/json',
64
            ],
65
            'auth' => [
66
                $this->config['app'], $this->config['secret']
67
            ],
68
            'base_uri' => $this->config['domain'].':'.$this->config['port'],
69
            'debug' => $this->config['debug'],
70
            'http_errors' => false,
71
            'verify' => false
72
        ]);
73
        return $client;
74
    }
75
76
    /**
77
     * Starts the recording of a {@see Session}
78
     * @param  RecordingProperties  $properties
79
     * @return Recording
80
     * @throws OpenViduException
81
     * @throws OpenViduRecordingResolutionException
82
     * @throws OpenViduServerRecordingIsDisabledException
83
     * @throws OpenViduSessionCantRecordingException
84
     * @throws OpenViduSessionHasNotConnectedParticipantsException
85
     * @throws OpenViduSessionNotFoundException
86
     * @throws InvalidArgumentException
87
     * @throws Exceptions\OpenViduInvalidArgumentException
88
     */
89
    public function startRecording(RecordingProperties $properties): Recording
90
    {
91
        $response = $this->client()->post(Uri::RECORDINGS_START, [
92
            RequestOptions::JSON => $properties->toArray() ?? null
93
        ]);
94
        switch ($response->getStatusCode()) {
95
            case 200:
96
                $recording = RecordingBuilder::build(json_decode($response->getBody()->getContents(), true));
97
                $activeSession = $this->getSession($recording->getSessionId());
98
                if ($activeSession != null) {
99
                    $activeSession->setIsBeingRecorded(true);
100
                }
101
                return $recording;
102
            case 404:
103
                throw new OpenViduSessionNotFoundException();
104
                break;
105
            case 406:
106
                throw new OpenViduSessionHasNotConnectedParticipantsException();
107
                break;
108
            case 409:
109
                throw new OpenViduSessionCantRecordingException("The session is not configured for using media routed or it is already being recorded");
110
                break;
111
            case 422:
112
                throw new OpenViduRecordingResolutionException();
113
                break;
114
            case 501:
115
                throw new OpenViduServerRecordingIsDisabledException();
116
                break;
117
            default:
118
                throw new OpenViduException("Invalid response status code ".$response->getStatusCode(), $response->getStatusCode());
119
        }
120
    }
121
122
    /**
123
     * Gets an existing {@see Session}
124
     * @param  string  $sessionId
125
     * @return Session
126
     * @throws OpenViduException
127
     * @throws OpenViduSessionNotFoundException
128
     * @throws InvalidArgumentException
129
     */
130
    public function getSession(string $sessionId): Session
131
    {
132
        if (Cache::store('openvidu')->has($sessionId)) {
133
            return (new Session($this->client()))->fromJson(Cache::store('openvidu')->get($sessionId));
134
        }
135
        throw new OpenViduSessionNotFoundException();
136
    }
137
138
139
    /**
140
     * Check if exists {@see Session}
141
     * @param  string  $sessionId
142
     * @return bool
143
     * @throws InvalidArgumentException
144
     */
145
    public function existsSession(string $sessionId): bool
146
    {
147
        return Cache::store('openvidu')->has($sessionId);
148
    }
149
150
    /**
151
     * Stops the recording of a {@see Session}
152
     * @param  string  $recordingId  The `id` property of the {@see Recording} you want to stop
153
     * @return Recording
154
     * @throws OpenViduException
155
     * @throws OpenViduRecordingNotFoundException
156
     * @throws OpenViduRecordingStatusException
157
     * @throws OpenViduSessionNotFoundException
158
     * @throws InvalidArgumentException
159
     * @throws Exceptions\OpenViduInvalidArgumentException
160
     */
161
    public function stopRecording(string $recordingId): Recording
162
    {
163
        $response = $this->client()->post(Uri::RECORDINGS_STOP.'/'.$recordingId);
164
        switch ($response->getStatusCode()) {
165
            case 200:
166
                $recording = RecordingBuilder::build(json_decode($response->getBody()->getContents(), true));
167
                $activeSession = $this->getSession($recording->getSessionId());
168
                if ($activeSession != null) {
169
                    $activeSession->setIsBeingRecorded(false);
170
                }
171
                return $recording;
172
            case 404:
173
                throw new OpenViduRecordingNotFoundException();
174
                break;
175
            case 406:
176
                throw new OpenViduRecordingStatusException("The recording has `starting` status. Wait until `started` status before stopping the recording.");
177
                break;
178
            default:
179
                throw new OpenViduException("Invalid response status code ".$response->getStatusCode(), $response->getStatusCode());
180
        }
181
    }
182
183
    /**
184
     * Gets an existing {@see Recording}
185
     * @param  string  $recordingId  The `id` property of the {@see Recording} you want to retrieve
186
     * @return string
187
     * @throws OpenViduException
188
     * @throws OpenViduRecordingNotFoundException
189
     * @throws Exceptions\OpenViduInvalidArgumentException
190
     */
191
    public function getRecording(string $recordingId): string
192
    {
193
        $response = $this->client()->get(Uri::RECORDINGS_URI.'/'.$recordingId);
194
        switch ($response->getStatusCode()) {
195
            case 200:
196
                $recording = RecordingBuilder::build(json_decode($response->getBody()->getContents(), true));
197
                return $recording;
198
            case 404:
199
                throw new OpenViduRecordingNotFoundException();
200
                break;
201
            default:
202
                throw new OpenViduException("Invalid response status code ".$response->getStatusCode(), $response->getStatusCode());
203
        }
204
    }
205
206
    /**
207
     * Gets an array with all existing recordings
208
     * @return array
209
     * @throws OpenViduException
210
     * @throws Exceptions\OpenViduInvalidArgumentException
211
     */
212
    public function getRecordings(): array
213
    {
214
        $recordings = [];
215
        $response = $this->client()->get(Uri::RECORDINGS_URI);
216
        switch ($response->getStatusCode()) {
217
            case 200:
218
                $items = json_decode($response->getBody()->getContents(), true);
219
                foreach ($items as $item) {
220
                    $recordings[] = RecordingBuilder::build($item);
221
                }
222
                return $recordings;
223
            default:
224
                throw new OpenViduException("Invalid response status code ".$response->getStatusCode(), $response->getStatusCode());
225
        }
226
    }
227
228
229
    /**
230
     * Deletes a {@see Recording}. The recording must have status `stopped`, `ready` or `failed`
231
     * @param  string  $recordingId  The `id` property of the {@see Recording} you want to delete
232
     * @return bool
233
     * @throws OpenViduException
234
     * @throws OpenViduRecordingNotFoundException
235
     * @throws OpenViduRecordingStatusException
236
     */
237
    public function deleteRecording(string $recordingId): bool
238
    {
239
        $response = $this->client()->delete(Uri::RECORDINGS_URI.'/'.$recordingId);
240
241
        switch ($response->getStatusCode()) {
242
            case 200:
243
                return true;
244
            case 404:
245
                throw new OpenViduRecordingNotFoundException();
246
                break;
247
            case 409:
248
                throw new OpenViduRecordingStatusException("The recording has `started` status. Stop it before deletion.");
249
                break;
250
            default:
251
                throw new OpenViduException("Invalid response status code ".$response->getStatusCode(), $response->getStatusCode());
252
        }
253
    }
254
255
    /**
256
     * Returns the list of active sessions. <strong>This value will remain unchanged
257
     * since the last time method {@link SquareetLabs\LaravelOpenVidu#fetch()}
258
     * was called</strong>. Exceptions to this rule are:
259
     * <ul>
260
     * <li>Calling {@see Session::fetch} updates that
261
     * specific Session status</li>
262
     * <li>Calling {@see Session::close()} automatically
263
     * removes the Session from the list of active Sessions</li>
264
     * <li>Calling
265
     * {@see Session::forceDisconnect(string)}
266
     * automatically updates the inner affected connections for that specific
267
     * Session</li>
268
     * <li>Calling {@see Session::forceUnpublish(string)}
269
     * also automatically updates the inner affected connections for that specific
270
     * Session</li>
271
     * <li>Calling {@see OpenVidu::startRecording(string)}
272
     * and {@see LaravelOpenVidu::stopRecording(string)}
273
     * automatically updates the recording status of the Session
274
     * </ul>
275
     * <br>
276
     * To get the list of active sessions with their current actual value, you must
277
     * call first {@see OpenVidu::fetch()} and then
278
     * {@see OpenVidu::getActiveSessions()}
279
     * @throws OpenViduException
280
     */
281
    public function getActiveSessions(): array
282
    {
283
        try {
284
            return Cache::store('openvidu')->getAll();
285
        } catch (Exception $e) {
286
            throw new OpenViduException("Make sure you have correctly configured the openvidu cache driver.", 500);
287
        }
288
    }
289
}
290
291