Passed
Push — master ( c62279...bc17cc )
by Ankit
02:04
created

Client::isExpired()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace TusPhp\Tus;
4
5
use TusPhp\File;
6
use Carbon\Carbon;
7
use TusPhp\Config;
8
use TusPhp\Exception\TusException;
9
use TusPhp\Exception\FileException;
10
use GuzzleHttp\Client as GuzzleClient;
11
use GuzzleHttp\Exception\ClientException;
12
use TusPhp\Exception\ConnectionException;
13
use GuzzleHttp\Exception\ConnectException;
14
use Symfony\Component\HttpFoundation\Response as HttpResponse;
15
16
class Client extends AbstractTus
17
{
18
    /** @var GuzzleClient */
19
    protected $client;
20
21
    /** @var string */
22
    protected $filePath;
23
24
    /** @var int */
25
    protected $fileSize = 0;
26
27
    /** @var string */
28
    protected $fileName;
29
30
    /** @var string */
31
    protected $key;
32
33
    /** @var string */
34
    protected $url;
35
36
    /** @var string */
37
    protected $checksum;
38
39
    /** @var int */
40
    protected $partialOffset = -1;
41
42
    /** @var bool */
43
    protected $partial = false;
44
45
    /** @var string */
46
    protected $checksumAlgorithm = 'sha256';
47
48
    /**
49
     * Client constructor.
50
     *
51
     * @param string $baseUri
52
     * @param array  $options
53
     *
54
     * @throws \ReflectionException
55
     */
56 3
    public function __construct(string $baseUri, array $options = [])
57
    {
58 3
        $options['headers'] = [
59 3
            'Tus-Resumable' => self::TUS_PROTOCOL_VERSION,
60 3
        ] + ($options['headers'] ?? []);
61
62 3
        $this->client = new GuzzleClient(
63 3
            ['base_uri' => $baseUri] + $options
64
        );
65
66 3
        Config::set(__DIR__ . '/../Config/client.php');
67
68 3
        $this->setCache('file');
69 3
    }
70
71
    /**
72
     * Set file properties.
73
     *
74
     * @param string $file File path.
75
     * @param string $name File name.
76
     *
77
     * @return Client
78
     */
79 3
    public function file(string $file, string $name = null) : self
80
    {
81 3
        $this->filePath = $file;
82
83 3
        if ( ! file_exists($file) || ! is_readable($file)) {
84 2
            throw new FileException('Cannot read file: ' . $file);
85
        }
86
87 1
        $this->fileName = $name ?? basename($this->filePath);
88 1
        $this->fileSize = filesize($file);
89
90 1
        return $this;
91
    }
92
93
    /**
94
     * Get file path.
95
     *
96
     * @return string|null
97
     */
98 1
    public function getFilePath() : ?string
99
    {
100 1
        return $this->filePath;
101
    }
102
103
    /**
104
     * Set file name.
105
     *
106
     * @param string $name
107
     *
108
     * @return Client
109
     */
110 1
    public function setFileName(string $name) : self
111
    {
112 1
        $this->fileName = $name;
113
114 1
        return $this;
115
    }
116
117
    /**
118
     * Get file name.
119
     *
120
     * @return string|null
121
     */
122 2
    public function getFileName() : ?string
123
    {
124 2
        return $this->fileName;
125
    }
126
127
    /**
128
     * Get file size.
129
     *
130
     * @return int
131
     */
132 1
    public function getFileSize() : int
133
    {
134 1
        return $this->fileSize;
135
    }
136
137
    /**
138
     * Get guzzle client.
139
     *
140
     * @return GuzzleClient
141
     */
142 2
    public function getClient() : GuzzleClient
143
    {
144 2
        return $this->client;
145
    }
146
147
    /**
148
     * Get checksum.
149
     *
150
     * @return string
151
     */
152 1
    public function getChecksum() : string
153
    {
154 1
        if (empty($this->checksum)) {
155 1
            $this->checksum = hash_file($this->getChecksumAlgorithm(), $this->getFilePath());
156
        }
157
158 1
        return $this->checksum;
159
    }
160
161
    /**
162
     * Set key.
163
     *
164
     * @param string $key
165
     *
166
     * @return Client
167
     */
168 1
    public function setKey(string $key) : self
169
    {
170 1
        $this->key = $key;
171
172 1
        return $this;
173
    }
174
175
    /**
176
     * Get key.
177
     *
178
     * @return string
179
     */
180 1
    public function getKey() : string
181
    {
182 1
        return $this->key;
183
    }
184
185
    /**
186
     * Get url.
187
     *
188
     * @return string|null
189
     */
190 2
    public function getUrl() : ?string
191
    {
192 2
        $this->url = $this->getCache()->get($this->getKey())['location'] ?? null;
193
194 2
        if ( ! $this->url) {
195 1
            throw new FileException('File not found.');
196
        }
197
198 1
        return $this->url;
199
    }
200
201
    /**
202
     * Set checksum algorithm.
203
     *
204
     * @param string $algorithm
205
     *
206
     * @return Client
207
     */
208 1
    public function setChecksumAlgorithm(string $algorithm) : self
209
    {
210 1
        $this->checksumAlgorithm = $algorithm;
211
212 1
        return $this;
213
    }
214
215
    /**
216
     * Get checksum algorithm.
217
     *
218
     * @return string
219
     */
220 1
    public function getChecksumAlgorithm() : string
221
    {
222 1
        return $this->checksumAlgorithm;
223
    }
224
225
    /**
226
     * Check if current upload is expired.
227
     *
228
     * @return bool
229
     */
230 2
    public function isExpired() : bool
231
    {
232 2
        $expiresAt = $this->getCache()->get($this->getKey())['expires_at'] ?? null;
233
234 2
        return empty($expiresAt) || Carbon::parse($expiresAt)->lt(Carbon::now());
235
    }
236
237
    /**
238
     * Check if this is a partial upload request.
239
     *
240
     * @return bool
241
     */
242 2
    public function isPartial() : bool
243
    {
244 2
        return $this->partial;
245
    }
246
247
    /**
248
     * Get partial offset.
249
     *
250
     * @return int
251
     */
252 1
    public function getPartialOffset() : int
253
    {
254 1
        return $this->partialOffset;
255
    }
256
257
    /**
258
     * Set offset and force this to be a partial upload request.
259
     *
260
     * @param int $offset
261
     *
262
     * @return self
263
     */
264 1
    public function seek(int $offset) : self
265
    {
266 1
        $this->partialOffset = $offset;
267
268 1
        $this->partial();
269
270 1
        return $this;
271
    }
272
273
    /**
274
     * Upload file.
275
     *
276
     * @param int $bytes Bytes to upload
277
     *
278
     * @throws TusException
279
     * @throws ConnectionException
280
     *
281
     * @return int
282
     */
283 6
    public function upload(int $bytes = -1) : int
284
    {
285 6
        $bytes  = $bytes < 0 ? $this->getFileSize() : $bytes;
286 6
        $offset = $this->partialOffset < 0 ? 0 : $this->partialOffset;
0 ignored issues
show
Unused Code introduced by
The assignment to $offset is dead and can be removed.
Loading history...
287
288
        try {
289
            // Check if this upload exists with HEAD request.
290 6
            $offset = $this->sendHeadRequest();
291 3
        } catch (FileException | ClientException $e) {
292
            // Create a new upload.
293 2
            $this->url = $this->create($this->getKey());
294 1
        } catch (ConnectException $e) {
295 1
            throw new ConnectionException("Couldn't connect to server.");
296
        }
297
298
        // Verify that upload is not yet expired.
299 5
        if ($this->isExpired()) {
300 1
            throw new TusException('Upload expired.');
301
        }
302
303
        // Now, resume upload with PATCH request.
304 4
        return $this->sendPatchRequest($bytes, $offset);
305
    }
306
307
    /**
308
     * Returns offset if file is partially uploaded.
309
     *
310
     * @return bool|int
311
     */
312 3
    public function getOffset()
313
    {
314
        try {
315 3
            $offset = $this->sendHeadRequest();
316 2
        } catch (FileException | ClientException $e) {
317 2
            return false;
318
        }
319
320 1
        return $offset;
321
    }
322
323
    /**
324
     * Create resource with POST request.
325
     *
326
     * @param string $key
327
     *
328
     * @throws FileException
329
     *
330
     * @return string
331
     */
332 3
    public function create(string $key) : string
333
    {
334
        $headers = [
335 3
            'Upload-Length' => $this->fileSize,
336 3
            'Upload-Key' => $key,
337 3
            'Upload-Checksum' => $this->getUploadChecksumHeader(),
338 3
            'Upload-Metadata' => 'filename ' . base64_encode($this->fileName),
339
        ];
340
341 3
        if ($this->isPartial()) {
342 1
            $headers += ['Upload-Concat' => 'partial'];
343
        }
344
345 3
        $response = $this->getClient()->post($this->apiPath, [
346 3
            'headers' => $headers,
347
        ]);
348
349 3
        $statusCode = $response->getStatusCode();
350
351 3
        if (HttpResponse::HTTP_CREATED !== $statusCode) {
352 1
            throw new FileException('Unable to create resource.');
353
        }
354
355 2
        $uploadLocation = current($response->getHeader('location'));
356
357 2
        $this->getCache()->set($this->getKey(), [
358 2
            'location' => $uploadLocation,
359 2
            'expires_at' => Carbon::now()->addSeconds($this->getCache()->getTtl())->format($this->getCache()::RFC_7231),
360
        ]);
361
362 2
        return $uploadLocation;
363
    }
364
365
    /**
366
     * Concatenate 2 or more partial uploads.
367
     *
368
     * @param string $key
369
     * @param mixed  $partials
370
     *
371
     * @return string
372
     */
373 3
    public function concat(string $key, ...$partials) : string
374
    {
375 3
        $response = $this->getClient()->post($this->apiPath, [
376
            'headers' => [
377 3
                'Upload-Length' => $this->fileSize,
378 3
                'Upload-Key' => $key,
379 3
                'Upload-Checksum' => $this->getUploadChecksumHeader(),
380 3
                'Upload-Metadata' => 'filename ' . base64_encode($this->fileName),
381 3
                'Upload-Concat' => self::UPLOAD_TYPE_FINAL . ';' . implode(' ', $partials),
382
            ],
383
        ]);
384
385 3
        $data       = json_decode($response->getBody(), true);
386 3
        $checksum   = $data['data']['checksum'] ?? null;
387 3
        $statusCode = $response->getStatusCode();
388
389 3
        if (HttpResponse::HTTP_CREATED !== $statusCode || ! $checksum) {
390 2
            throw new FileException('Unable to create resource.');
391
        }
392
393 1
        return $checksum;
394
    }
395
396
    /**
397
     * Send DELETE request.
398
     *
399
     * @throws FileException
400
     *
401
     * @return void
402
     */
403 3
    public function delete()
404
    {
405
        try {
406 3
            $this->getClient()->delete($this->getUrl());
407 2
        } catch (ClientException $e) {
408 2
            $statusCode = $e->getResponse()->getStatusCode();
409
410 2
            if (HttpResponse::HTTP_NOT_FOUND === $statusCode || HttpResponse::HTTP_GONE === $statusCode) {
411 2
                throw new FileException('File not found.');
412
            }
413
        }
414 1
    }
415
416
    /**
417
     * Set as partial request.
418
     *
419
     * @param bool $state
420
     *
421
     * @return void
422
     */
423 3
    protected function partial(bool $state = true)
424
    {
425 3
        $this->partial = $state;
426
427 3
        if ( ! $this->partial) {
428 1
            return;
429
        }
430
431 2
        $key = $this->getKey();
432
433 2
        if (false !== strpos($key, self::PARTIAL_UPLOAD_NAME_SEPARATOR)) {
434 1
            list($key, /* $partialKey */) = explode(self::PARTIAL_UPLOAD_NAME_SEPARATOR, $key);
435
        }
436
437 2
        $this->key = $key . uniqid(self::PARTIAL_UPLOAD_NAME_SEPARATOR);
438 2
    }
439
440
    /**
441
     * Send HEAD request.
442
     *
443
     * @throws FileException
444
     *
445
     * @return int
446
     */
447 2
    protected function sendHeadRequest() : int
448
    {
449 2
        $response   = $this->getClient()->head($this->getUrl());
450 2
        $statusCode = $response->getStatusCode();
451
452 2
        if (HttpResponse::HTTP_OK !== $statusCode) {
453 1
            throw new FileException('File not found.');
454
        }
455
456 1
        return (int) current($response->getHeader('upload-offset'));
457
    }
458
459
    /**
460
     * Send PATCH request.
461
     *
462
     * @param int $bytes
463
     * @param int $offset
464
     *
465
     * @throws TusException
466
     * @throws FileException
467
     * @throws ConnectionException
468
     *
469
     * @return int
470
     */
471 7
    protected function sendPatchRequest(int $bytes, int $offset) : int
472
    {
473 7
        $data    = $this->getData($offset, $bytes);
474
        $headers = [
475 7
            'Content-Type' => self::HEADER_CONTENT_TYPE,
476 7
            'Content-Length' => strlen($data),
477 7
            'Upload-Checksum' => $this->getUploadChecksumHeader(),
478
        ];
479
480 7
        if ($this->isPartial()) {
481 1
            $headers += ['Upload-Concat' => self::UPLOAD_TYPE_PARTIAL];
482
        } else {
483 6
            $headers += ['Upload-Offset' => $offset];
484
        }
485
486
        try {
487 7
            $response = $this->getClient()->patch($this->getUrl(), [
488 7
                'body' => $data,
489 7
                'headers' => $headers,
490
            ]);
491
492 2
            return (int) current($response->getHeader('upload-offset'));
493 5
        } catch (ClientException $e) {
494 4
            throw $this->handleClientException($e);
495 1
        } catch (ConnectException $e) {
496 1
            throw new ConnectionException("Couldn't connect to server.");
497
        }
498
    }
499
500
    /**
501
     * Handle client exception during patch request.
502
     *
503
     * @param ClientException $e
504
     *
505
     * @return mixed
506
     */
507 4
    protected function handleClientException(ClientException $e)
508
    {
509 4
        $statusCode = $e->getResponse()->getStatusCode();
510
511 4
        if (HttpResponse::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE === $statusCode) {
512 1
            return new FileException('The uploaded file is corrupt.');
513
        }
514
515 3
        if (HttpResponse::HTTP_CONTINUE === $statusCode) {
516 1
            return new ConnectionException('Connection aborted by user.');
517
        }
518
519 2
        if (HttpResponse::HTTP_UNSUPPORTED_MEDIA_TYPE === $statusCode) {
520 1
            return new TusException('Unsupported media types.');
521
        }
522
523 1
        return new TusException($e->getResponse()->getBody(), $statusCode);
524
    }
525
526
    /**
527
     * Get X bytes of data from file.
528
     *
529
     * @param int $offset
530
     * @param int $bytes
531
     *
532
     * @return string
533
     */
534 2
    protected function getData(int $offset, int $bytes) : string
535
    {
536 2
        $file   = new File;
537 2
        $handle = $file->open($this->getFilePath(), $file::READ_BINARY);
538
539 2
        $file->seek($handle, $offset);
540
541 2
        $data = $file->read($handle, $bytes);
542
543 2
        $file->close($handle);
544
545 2
        return (string) $data;
546
    }
547
548
    /**
549
     * Get upload checksum header.
550
     *
551
     * @return string
552
     */
553 1
    protected function getUploadChecksumHeader() : string
554
    {
555 1
        return $this->getChecksumAlgorithm() . ' ' . base64_encode($this->getChecksum());
556
    }
557
}
558