Passed
Branch master (6df2dd)
by Jacobo
06:45 queued 03:04
created

OpenVidu::stopRecording()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 16
c 0
b 0
f 0
nc 5
nop 1
dl 0
loc 19
rs 9.4222
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|null $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 = null): Recording
90
    {
91
        $response = $this->client()->post(Uri::RECORDINGS_START, [
92
            RequestOptions::JSON => $properties->toArray() ?? null
0 ignored issues
show
Bug introduced by
The method toArray() does not exist on null. ( Ignorable by Annotation )

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

92
            RequestOptions::JSON => $properties->/** @scrutinizer ignore-call */ toArray() ?? null

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
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
     * Stops the recording of a {@see Session}
140
     * @param string $recordingId The `id` property of the {@see Recording} you want to stop
141
     * @return Recording
142
     * @throws OpenViduException
143
     * @throws OpenViduRecordingNotFoundException
144
     * @throws OpenViduRecordingStatusException
145
     * @throws OpenViduSessionNotFoundException
146
     * @throws InvalidArgumentException
147
     * @throws Exceptions\OpenViduInvalidArgumentException
148
     */
149
    public function stopRecording(string $recordingId): Recording
150
    {
151
        $response = $this->client()->post(Uri::RECORDINGS_STOP . '/' . $recordingId);
152
        switch ($response->getStatusCode()) {
153
            case 200:
154
                $recording = RecordingBuilder::build(json_decode($response->getBody()->getContents(), true));
155
                $activeSession = $this->getSession($recording->getSessionId());
156
                if ($activeSession != null) {
157
                    $activeSession->setIsBeingRecorded(false);
158
                }
159
                return $recording;
160
            case 404:
161
                throw new OpenViduRecordingNotFoundException();
162
                break;
163
            case 406:
164
                throw new OpenViduRecordingStatusException("The recording has `starting` status. Wait until `started` status before stopping the recording.");
165
                break;
166
            default:
167
                throw new OpenViduException("Invalid response status code " . $response->getStatusCode(), $response->getStatusCode());
168
        }
169
    }
170
171
    /**
172
     * Gets an existing {@see Recording}
173
     * @param string $recordingId The `id` property of the {@see Recording} you want to retrieve
174
     * @return string
175
     * @throws OpenViduException
176
     * @throws OpenViduRecordingNotFoundException
177
     * @throws Exceptions\OpenViduInvalidArgumentException
178
     */
179
    public function getRecording(string $recordingId): string
180
    {
181
        $response = $this->client()->get(Uri::RECORDINGS_URI . '/' . $recordingId);
182
        switch ($response->getStatusCode()) {
183
            case 200:
184
                $recording = RecordingBuilder::build(json_decode($response->getBody()->getContents(), true));
185
                return $recording;
186
            case 404:
187
                throw new OpenViduRecordingNotFoundException();
188
                break;
189
            default:
190
                throw new OpenViduException("Invalid response status code " . $response->getStatusCode(), $response->getStatusCode());
191
        }
192
    }
193
194
    /**
195
     * Gets an array with all existing recordings
196
     * @return array
197
     * @throws OpenViduException
198
     * @throws Exceptions\OpenViduInvalidArgumentException
199
     */
200
    public function getRecordings(): array
201
    {
202
        $recordings = [];
203
        $response = $this->client()->get(Uri::RECORDINGS_URI);
204
        switch ($response->getStatusCode()) {
205
            case 200:
206
                $items = json_decode($response->getBody()->getContents(), true);
207
                foreach ($items as $item) {
208
                    $recordings[] = RecordingBuilder::build($item);
209
                }
210
                return $recordings;
211
            default:
212
                throw new OpenViduException("Invalid response status code " . $response->getStatusCode(), $response->getStatusCode());
213
        }
214
    }
215
216
217
    /**
218
     * Deletes a {@see Recording}. The recording must have status `stopped`, `ready` or `failed`
219
     * @param string $recordingId The `id` property of the {@see Recording} you want to delete
220
     * @return bool
221
     * @throws OpenViduException
222
     * @throws OpenViduRecordingNotFoundException
223
     * @throws OpenViduRecordingStatusException
224
     */
225
    public function deleteRecording(string $recordingId): bool
226
    {
227
        $response = $this->client()->delete(Uri::RECORDINGS_URI . '/' . $recordingId);
228
229
        switch ($response->getStatusCode()) {
230
            case 200:
231
                return true;
232
            case 404:
233
                throw new OpenViduRecordingNotFoundException();
234
                break;
235
            case 409:
236
                throw new OpenViduRecordingStatusException("The recording has `started` status. Stop it before deletion.");
237
                break;
238
            default:
239
                throw new OpenViduException("Invalid response status code " . $response->getStatusCode(), $response->getStatusCode());
240
        }
241
    }
242
243
    /**
244
     * Returns the list of active sessions. <strong>This value will remain unchanged
245
     * since the last time method {@link SquareetLabs\LaravelOpenVidu#fetch()}
246
     * was called</strong>. Exceptions to this rule are:
247
     * <ul>
248
     * <li>Calling {@see Session::fetch} updates that
249
     * specific Session status</li>
250
     * <li>Calling {@see Session::close()} automatically
251
     * removes the Session from the list of active Sessions</li>
252
     * <li>Calling
253
     * {@see Session::forceDisconnect(string)}
254
     * automatically updates the inner affected connections for that specific
255
     * Session</li>
256
     * <li>Calling {@see Session::forceUnpublish(string)}
257
     * also automatically updates the inner affected connections for that specific
258
     * Session</li>
259
     * <li>Calling {@see OpenVidu::startRecording(string)}
260
     * and {@see LaravelOpenVidu::stopRecording(string)}
261
     * automatically updates the recording status of the Session
262
     * </ul>
263
     * <br>
264
     * To get the list of active sessions with their current actual value, you must
265
     * call first {@see OpenVidu::fetch()} and then
266
     * {@see OpenVidu::getActiveSessions()}
267
     * @throws OpenViduException
268
     */
269
    public function getActiveSessions(): array
270
    {
271
        try {
272
            return Cache::store('openvidu')->getAll();
273
        } catch (Exception $e) {
274
            throw new OpenViduException("Make sure you have correctly configured the openvidu cache driver.", 500);
275
        }
276
    }
277
}
278
279