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