Completed
Pull Request — master (#31)
by Ankit
02:27
created

Server::headers()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 2
rs 9.6666
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A Server::getMaxUploadSize() 0 3 1
1
<?php
2
3
namespace TusPhp\Tus;
4
5
use TusPhp\File;
6
use Carbon\Carbon;
7
use TusPhp\Request;
8
use TusPhp\Response;
9
use Ramsey\Uuid\Uuid;
10
use TusPhp\Cache\Cacheable;
11
use TusPhp\Middleware\Middleware;
12
use TusPhp\Exception\FileException;
13
use TusPhp\Exception\ConnectionException;
14
use TusPhp\Exception\OutOfRangeException;
15
use Illuminate\Http\Response as HttpResponse;
16
use Symfony\Component\HttpFoundation\BinaryFileResponse;
17
18
class Server extends AbstractTus
19
{
20
    /** @const string Tus Creation Extension */
21
    const TUS_EXTENSION_CREATION = 'creation';
22
23
    /** @const string Tus Termination Extension */
24
    const TUS_EXTENSION_TERMINATION = 'termination';
25
26
    /** @const string Tus Checksum Extension */
27
    const TUS_EXTENSION_CHECKSUM = 'checksum';
28
29
    /** @const string Tus Expiration Extension */
30
    const TUS_EXTENSION_EXPIRATION = 'expiration';
31
32
    /** @const string Tus Concatenation Extension */
33
    const TUS_EXTENSION_CONCATENATION = 'concatenation';
34
35
    /** @const array All supported tus extensions */
36
    const TUS_EXTENSIONS = [
37
        self::TUS_EXTENSION_CREATION,
38
        self::TUS_EXTENSION_TERMINATION,
39
        self::TUS_EXTENSION_CHECKSUM,
40
        self::TUS_EXTENSION_EXPIRATION,
41
        self::TUS_EXTENSION_CONCATENATION,
42
    ];
43
44
    /** @const int 460 Checksum Mismatch */
45
    const HTTP_CHECKSUM_MISMATCH = 460;
46
47
    /** @const string Default checksum algorithm */
48
    const DEFAULT_CHECKSUM_ALGORITHM = 'sha256';
49
50
    /** @var Request */
51
    protected $request;
52
53
    /** @var Response */
54
    protected $response;
55
56
    /** @var string */
57
    protected $uploadDir;
58
59
    /** @var string */
60
    protected $uploadKey;
61
62
    /** @var Middleware */
63
    protected $middleware;
64
65
    /**
66
     * @var int Max upload size in bytes
67
     *          Default 0, no restriction.
68
     */
69
    protected $maxUploadSize = 0;
70
71
    /**
72
     * TusServer constructor.
73
     *
74
     * @param Cacheable|string $cacheAdapter
75
     */
76 3
    public function __construct($cacheAdapter = 'file')
77
    {
78 3
        $this->request    = new Request;
79 3
        $this->response   = new Response;
80 3
        $this->middleware = new Middleware;
81 3
        $this->uploadDir  = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'uploads';
82
83 3
        $this->setCache($cacheAdapter);
84 3
    }
85
86
    /**
87
     * Set upload dir.
88
     *
89
     * @param string $path
90
     *
91
     * @return Server
92
     */
93 2
    public function setUploadDir(string $path) : self
94
    {
95 2
        $this->uploadDir = $path;
96
97 2
        return $this;
98
    }
99
100
    /**
101
     * Get upload dir.
102
     *
103
     * @return string
104
     */
105 1
    public function getUploadDir() : string
106
    {
107 1
        return $this->uploadDir;
108
    }
109
110
    /**
111
     * Get request.
112
     *
113
     * @return Request
114
     */
115 1
    public function getRequest() : Request
116
    {
117 1
        return $this->request;
118
    }
119
120
    /**
121
     * Get request.
122
     *
123
     * @return Response
124
     */
125 1
    public function getResponse() : Response
126
    {
127 1
        return $this->response;
128
    }
129
130
    /**
131
     * Get file checksum.
132
     *
133
     * @param string $filePath
134
     *
135
     * @return string
136
     */
137 1
    public function getServerChecksum(string $filePath) : string
138
    {
139 1
        return hash_file($this->getChecksumAlgorithm(), $filePath);
140
    }
141
142
    /**
143
     * Get checksum algorithm.
144
     *
145
     * @return string|null
146
     */
147 1
    public function getChecksumAlgorithm()
148
    {
149 1
        $checksumHeader = $this->getRequest()->header('Upload-Checksum');
150
151 1
        if (empty($checksumHeader)) {
152 1
            return self::DEFAULT_CHECKSUM_ALGORITHM;
153
        }
154
155 1
        list($checksumAlgorithm) = explode(' ', $checksumHeader);
156
157 1
        return $checksumAlgorithm;
158
    }
159
160
    /**
161
     * Set upload key.
162
     *
163
     * @param string $key
164
     *
165
     * @return Server
166
     */
167 1
    public function setUploadKey(string $key) : self
168
    {
169 1
        $this->uploadKey = $key;
170
171 1
        return $this;
172
    }
173
174
    /**
175
     * Get upload key from header.
176
     *
177
     * @return string|HttpResponse
178
     */
179 4
    public function getUploadKey()
180
    {
181 4
        if ( ! empty($this->uploadKey)) {
182 1
            return $this->uploadKey;
183
        }
184
185 3
        $key = $this->getRequest()->header('Upload-Key') ?? Uuid::uuid4()->toString();
186
187 3
        if (empty($key)) {
188 1
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
189
        }
190
191 2
        $this->uploadKey = $key;
192
193 2
        return $this->uploadKey;
194
    }
195
196
    /**
197
     * Set middleware.
198
     *
199
     * @param Middleware $middleware
200
     *
201
     * @return self
202
     */
203 1
    public function setMiddleware(Middleware $middleware) : self
204
    {
205 1
        $this->middleware = $middleware;
206
207 1
        return $this;
208
    }
209
210
    /**
211
     * Get middleware.
212
     *
213
     * @return Middleware
214
     */
215 1
    public function middleware() : Middleware
216
    {
217 1
        return $this->middleware;
218
    }
219
220
    /**
221
     * Set max upload size.
222
     *
223
     * @param int $uploadSize
224
     *
225
     * @return Server
226
     */
227 2
    public function setMaxUploadSize(int $uploadSize) : self
228
    {
229 2
        $this->maxUploadSize = $uploadSize;
230
231 2
        return $this;
232
    }
233
234
    /**
235
     * Get max upload size.
236
     *
237
     * @return int
238
     */
239 1
    public function getMaxUploadSize() : int
240
    {
241 1
        return $this->maxUploadSize;
242
    }
243
244
    /**
245
     * Handle all HTTP request.
246
     *
247
     * @return HttpResponse
248
     */
249 3
    public function serve() : HttpResponse
250
    {
251 3
        $requestMethod = $this->getRequestMethod();
252
253 3
        if ( ! in_array($requestMethod, $this->getRequest()->allowedHttpVerbs())) {
254 1
            return $this->response->send(null, HttpResponse::HTTP_METHOD_NOT_ALLOWED);
255
        }
256
257 2
        $this->applyMiddleware();
258
259 2
        $method = 'handle' . ucfirst(strtolower($requestMethod));
260
261 2
        return $this->{$method}();
262
    }
263
264
    /**
265
     * Get actual request method.
266
     *
267
     * @return null|string
268
     */
269 1
    protected function getRequestMethod()
270
    {
271 1
        $request = $this->getRequest();
272
273 1
        $requestMethod = $request->method();
274
275
        // Allow overriding the HTTP method. The reason for this is
276
        // that some libraries/environments do not support PATCH and
277
        // DELETE requests, e.g. Flash in a browser and parts of Java.
278 1
        $newMethod = $request->header('X-HTTP-Method-Override');
279
280 1
        if ( ! empty($newMethod)) {
281 1
            $requestMethod = $newMethod;
282
        }
283
284 1
        return $requestMethod;
285
    }
286
287
    /**
288
     * Apply middleware.
289
     *
290
     * @return null
291
     */
292 1
    protected function applyMiddleware()
293
    {
294 1
        $middleware = $this->middleware()->list();
295
296 1
        foreach ($middleware as $m) {
297 1
            $m->handle($this->getRequest(), $this->getResponse());
298
        }
299 1
    }
300
301
    /**
302
     * Handle OPTIONS request.
303
     *
304
     * @return HttpResponse
305
     */
306 2
    protected function handleOptions() : HttpResponse
307
    {
308
        $headers = [
309 2
            'Allow' => implode(',', $this->request->allowedHttpVerbs()),
310 2
            'Tus-Version' => self::TUS_PROTOCOL_VERSION,
311 2
            'Tus-Extension' => implode(',', self::TUS_EXTENSIONS),
312 2
            'Tus-Checksum-Algorithm' => $this->getSupportedHashAlgorithms(),
313
        ];
314
315 2
        $maxUploadSize = $this->getMaxUploadSize();
316
317 2
        if ($maxUploadSize > 0) {
318 1
            $headers['Tus-Max-Size'] = $maxUploadSize;
319
        }
320
321 2
        return $this->response->send(null, HttpResponse::HTTP_OK, $headers);
322
    }
323
324
    /**
325
     * Handle HEAD request.
326
     *
327
     * @return HttpResponse
328
     */
329 5
    protected function handleHead() : HttpResponse
330
    {
331 5
        $key = $this->request->key();
332
333 5
        if ( ! $fileMeta = $this->cache->get($key)) {
334 1
            return $this->response->send(null, HttpResponse::HTTP_NOT_FOUND);
335
        }
336
337 4
        $offset = $fileMeta['offset'] ?? false;
338
339 4
        if (false === $offset) {
340 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
341
        }
342
343 3
        return $this->response->send(null, HttpResponse::HTTP_OK, $this->getHeadersForHeadRequest($fileMeta));
344
    }
345
346
    /**
347
     * Handle POST request.
348
     *
349
     * @return HttpResponse
350
     */
351 5
    protected function handlePost() : HttpResponse
352
    {
353 5
        $fileName   = $this->getRequest()->extractFileName();
354 5
        $uploadType = self::UPLOAD_TYPE_NORMAL;
355
356 5
        if (empty($fileName)) {
357 1
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
358
        }
359
360 4
        if ( ! $this->verifyUploadSize()) {
361 1
            return $this->response->send(null, HttpResponse::HTTP_REQUEST_ENTITY_TOO_LARGE);
362
        }
363
364 3
        $uploadKey = $this->getUploadKey();
365 3
        $filePath  = $this->uploadDir . DIRECTORY_SEPARATOR . $fileName;
366
367 3
        if ($this->getRequest()->isFinal()) {
368 1
            return $this->handleConcatenation($fileName, $filePath);
369
        }
370
371 2
        if ($this->getRequest()->isPartial()) {
372 1
            $filePath   = $this->getPathForPartialUpload($uploadKey) . $fileName;
373 1
            $uploadType = self::UPLOAD_TYPE_PARTIAL;
374
        }
375
376 2
        $checksum = $this->getClientChecksum();
377 2
        $location = $this->getRequest()->url() . $this->getApiPath() . '/' . $uploadKey;
378
379 2
        $file = $this->buildFile([
380 2
            'name' => $fileName,
381 2
            'offset' => 0,
382 2
            'size' => $this->getRequest()->header('Upload-Length'),
383 2
            'file_path' => $filePath,
384 2
            'location' => $location,
385 2
        ])->setChecksum($checksum);
386
387 2
        $this->cache->set($uploadKey, $file->details() + ['upload_type' => $uploadType]);
388
389 2
        return $this->response->send(
390 2
            ['data' => ['checksum' => $checksum]],
391 2
            HttpResponse::HTTP_CREATED,
392
            [
393 2
                'Location' => $location,
394 2
                'Upload-Expires' => $this->cache->get($uploadKey)['expires_at'],
395
            ]
396
        );
397
    }
398
399
    /**
400
     * Handle file concatenation.
401
     *
402
     * @param string $fileName
403
     * @param string $filePath
404
     *
405
     * @return HttpResponse
406
     */
407 2
    protected function handleConcatenation(string $fileName, string $filePath) : HttpResponse
408
    {
409 2
        $partials  = $this->getRequest()->extractPartials();
410 2
        $uploadKey = $this->getUploadKey();
411 2
        $files     = $this->getPartialsMeta($partials);
412 2
        $filePaths = array_column($files, 'file_path');
413 2
        $location  = $this->getRequest()->url() . $this->getApiPath() . '/' . $uploadKey;
414
415 2
        $file = $this->buildFile([
416 2
            'name' => $fileName,
417 2
            'offset' => 0,
418 2
            'size' => 0,
419 2
            'file_path' => $filePath,
420 2
            'location' => $location,
421 2
        ])->setFilePath($filePath);
422
423 2
        $file->setOffset($file->merge($files));
424
425
        // Verify checksum.
426 2
        $checksum = $this->getServerChecksum($filePath);
427
428 2
        if ($checksum !== $this->getClientChecksum()) {
429 1
            return $this->response->send(null, self::HTTP_CHECKSUM_MISMATCH);
430
        }
431
432 1
        $this->cache->set($uploadKey, $file->details() + ['upload_type' => self::UPLOAD_TYPE_FINAL]);
433
434
        // Cleanup.
435 1
        if ($file->delete($filePaths, true)) {
436 1
            $this->cache->deleteAll($partials);
437
        }
438
439 1
        return $this->response->send(
440 1
            ['data' => ['checksum' => $checksum]],
441 1
            HttpResponse::HTTP_CREATED,
442
            [
443 1
                'Location' => $location,
444
            ]
445
        );
446
    }
447
448
    /**
449
     * Handle PATCH request.
450
     *
451
     * @return HttpResponse
452
     */
453 7
    protected function handlePatch() : HttpResponse
454
    {
455 7
        $uploadKey = $this->request->key();
456
457 7
        if ( ! $meta = $this->cache->get($uploadKey)) {
458 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
459
        }
460
461 6
        if (self::UPLOAD_TYPE_FINAL === $meta['upload_type']) {
462 1
            return $this->response->send(null, HttpResponse::HTTP_FORBIDDEN);
463
        }
464
465 5
        $file     = $this->buildFile($meta);
466 5
        $checksum = $meta['checksum'];
467
468
        try {
469 5
            $fileSize = $file->getFileSize();
470 5
            $offset   = $file->setKey($uploadKey)->setChecksum($checksum)->upload($fileSize);
471
472
            // If upload is done, verify checksum.
473 2
            if ($offset === $fileSize && ! $this->verifyChecksum($checksum, $meta['file_path'])) {
474 2
                return $this->response->send(null, self::HTTP_CHECKSUM_MISMATCH);
475
            }
476 3
        } catch (FileException $e) {
477 1
            return $this->response->send($e->getMessage(), HttpResponse::HTTP_UNPROCESSABLE_ENTITY);
478 2
        } catch (OutOfRangeException $e) {
479 1
            return $this->response->send(null, HttpResponse::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE);
480 1
        } catch (ConnectionException $e) {
481 1
            return $this->response->send(null, HttpResponse::HTTP_CONTINUE);
482
        }
483
484 1
        return $this->response->send(null, HttpResponse::HTTP_NO_CONTENT, [
485 1
            'Content-Type' => 'application/offset+octet-stream',
486 1
            'Upload-Expires' => $this->cache->get($uploadKey)['expires_at'],
487 1
            'Upload-Offset' => $offset,
488
        ]);
489
    }
490
491
    /**
492
     * Handle GET request.
493
     *
494
     * @return BinaryFileResponse|HttpResponse
495
     */
496 4
    protected function handleGet()
497
    {
498 4
        $key = $this->request->key();
499
500 4
        if (empty($key)) {
501 1
            return $this->response->send('400 bad request.', HttpResponse::HTTP_BAD_REQUEST);
502
        }
503
504 3
        if ( ! $fileMeta = $this->cache->get($key)) {
505 1
            return $this->response->send('404 upload not found.', HttpResponse::HTTP_NOT_FOUND);
506
        }
507
508 2
        $resource = $fileMeta['file_path'] ?? null;
509 2
        $fileName = $fileMeta['name'] ?? null;
510
511 2
        if ( ! $resource || ! file_exists($resource)) {
512 1
            return $this->response->send('404 upload not found.', HttpResponse::HTTP_NOT_FOUND);
513
        }
514
515 1
        return $this->response->download($resource, $fileName);
516
    }
517
518
    /**
519
     * Handle DELETE request.
520
     *
521
     * @return HttpResponse
522
     */
523 3
    protected function handleDelete() : HttpResponse
524
    {
525 3
        $key      = $this->request->key();
526 3
        $fileMeta = $this->cache->get($key);
527 3
        $resource = $fileMeta['file_path'] ?? null;
528
529 3
        if ( ! $resource) {
530 1
            return $this->response->send(null, HttpResponse::HTTP_NOT_FOUND);
531
        }
532
533 2
        $isDeleted = $this->cache->delete($key);
534
535 2
        if ( ! $isDeleted || ! file_exists($resource)) {
536 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
537
        }
538
539 1
        unlink($resource);
540
541 1
        return $this->response->send(null, HttpResponse::HTTP_NO_CONTENT, [
542 1
            'Tus-Extension' => self::TUS_EXTENSION_TERMINATION,
543
        ]);
544
    }
545
546
    /**
547
     * Get required headers for head request.
548
     *
549
     * @param array $fileMeta
550
     *
551
     * @return array
552
     */
553 4
    protected function getHeadersForHeadRequest(array $fileMeta) : array
554
    {
555
        $headers = [
556 4
            'Upload-Length' => (int) $fileMeta['size'],
557 4
            'Upload-Offset' => (int) $fileMeta['offset'],
558 4
            'Cache-Control' => 'no-store',
559
        ];
560
561 4
        if (self::UPLOAD_TYPE_FINAL === $fileMeta['upload_type'] && $fileMeta['size'] !== $fileMeta['offset']) {
562 2
            unset($headers['Upload-Offset']);
563
        }
564
565 4
        if (self::UPLOAD_TYPE_NORMAL !== $fileMeta['upload_type']) {
566 3
            $headers += ['Upload-Concat' => $fileMeta['upload_type']];
567
        }
568
569 4
        return $headers;
570
    }
571
572
    /**
573
     * Build file object.
574
     *
575
     * @param array $meta
576
     *
577
     * @return File
578
     */
579 1
    protected function buildFile(array $meta) : File
580
    {
581 1
        $file = new File($meta['name'], $this->cache);
582
583 1
        if (array_key_exists('offset', $meta)) {
584 1
            $file->setMeta($meta['offset'], $meta['size'], $meta['file_path'], $meta['location']);
585
        }
586
587 1
        return $file;
588
    }
589
590
    /**
591
     * Get list of supported hash algorithms.
592
     *
593
     * @return string
594
     */
595 1
    protected function getSupportedHashAlgorithms() : string
596
    {
597 1
        $supportedAlgorithms = hash_algos();
598
599 1
        $algorithms = [];
600 1
        foreach ($supportedAlgorithms as $hashAlgo) {
601 1
            if (false !== strpos($hashAlgo, ',')) {
602 1
                $algorithms[] = "'{$hashAlgo}'";
603
            } else {
604 1
                $algorithms[] = $hashAlgo;
605
            }
606
        }
607
608 1
        return implode(',', $algorithms);
609
    }
610
611
    /**
612
     * Verify and get upload checksum from header.
613
     *
614
     * @return string|HttpResponse
615
     */
616 4
    protected function getClientChecksum()
617
    {
618 4
        $checksumHeader = $this->getRequest()->header('Upload-Checksum');
619
620 4
        if (empty($checksumHeader)) {
621 1
            return '';
622
        }
623
624 3
        list($checksumAlgorithm, $checksum) = explode(' ', $checksumHeader);
625
626 3
        $checksum = base64_decode($checksum);
627
628 3
        if ( ! in_array($checksumAlgorithm, hash_algos()) || false === $checksum) {
629 2
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
630
        }
631
632 1
        return $checksum;
633
    }
634
635
    /**
636
     * Get expired but incomplete uploads.
637
     *
638
     * @param array|null $contents
639
     *
640
     * @return bool
641
     */
642 3
    protected function isExpired($contents) : bool
643
    {
644 3
        $isExpired = empty($contents['expires_at']) || Carbon::parse($contents['expires_at'])->lt(Carbon::now());
645
646 3
        if ($isExpired && $contents['offset'] !== $contents['size']) {
647 3
            return true;
648
        }
649
650 2
        return false;
651
    }
652
653
    /**
654
     * Get path for partial upload.
655
     *
656
     * @param string $key
657
     *
658
     * @return string
659
     */
660 1
    protected function getPathForPartialUpload(string $key) : string
661
    {
662 1
        list($actualKey) = explode(self::PARTIAL_UPLOAD_NAME_SEPARATOR, $key);
663
664 1
        $path = $this->uploadDir . DIRECTORY_SEPARATOR . $actualKey . DIRECTORY_SEPARATOR;
665
666 1
        if ( ! file_exists($path)) {
667 1
            mkdir($path);
668
        }
669
670 1
        return $path;
671
    }
672
673
    /**
674
     * Get metadata of partials.
675
     *
676
     * @param array $partials
677
     *
678
     * @return array
679
     */
680 3
    protected function getPartialsMeta(array $partials) : array
681
    {
682 3
        $files = [];
683
684 3
        foreach ($partials as $partial) {
685 3
            $fileMeta = $this->getCache()->get($partial);
686
687 3
            $files[] = $fileMeta;
688
        }
689
690 3
        return $files;
691
    }
692
693
    /**
694
     * Delete expired resources.
695
     *
696
     * @return array
697
     */
698 2
    public function handleExpiration() : array
699
    {
700 2
        $deleted   = [];
701 2
        $cacheKeys = $this->cache->keys();
702
703 2
        foreach ($cacheKeys as $key) {
704 2
            $fileMeta = $this->cache->get($key, true);
705
706 2
            if ( ! $this->isExpired($fileMeta)) {
707 1
                continue;
708
            }
709
710 2
            if ( ! $this->cache->delete($key)) {
711 1
                continue;
712
            }
713
714 1
            if (is_writable($fileMeta['file_path'])) {
715 1
                unlink($fileMeta['file_path']);
716
            }
717
718 1
            $deleted[] = $fileMeta;
719
        }
720
721 2
        return $deleted;
722
    }
723
724
    /**
725
     * Verify max upload size.
726
     *
727
     * @return bool
728
     */
729 1
    protected function verifyUploadSize() : bool
730
    {
731 1
        $maxUploadSize = $this->getMaxUploadSize();
732
733 1
        if ($maxUploadSize > 0 && $this->getRequest()->header('Upload-Length') > $maxUploadSize) {
734 1
            return false;
735
        }
736
737 1
        return true;
738
    }
739
740
    /**
741
     * Verify checksum if available.
742
     *
743
     * @param string $checksum
744
     * @param string $filePath
745
     *
746
     * @return bool
747
     */
748 1
    protected function verifyChecksum(string $checksum, string $filePath) : bool
749
    {
750
        // Skip if checksum is empty.
751 1
        if (empty($checksum)) {
752 1
            return true;
753
        }
754
755 1
        return $checksum === $this->getServerChecksum($filePath);
756
    }
757
758
    /**
759
     * No other methods are allowed.
760
     *
761
     * @param string $method
762
     * @param array  $params
763
     *
764
     * @return HttpResponse|BinaryFileResponse
765
     */
766 1
    public function __call(string $method, array $params)
767
    {
768 1
        return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
769
    }
770
}
771