Passed
Push — master ( 5f68ae...cbdcc8 )
by Ankit
10:05
created

Client::createWithUpload()   B

Complexity

Conditions 7
Paths 48

Size

Total Lines 47
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 7

Importance

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