Completed
Pull Request — master (#21)
by Ankit
03:19
created

Server::setUploadKey()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 9.4285
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\Request;
8
use TusPhp\Response;
9
use Ramsey\Uuid\Uuid;
10
use TusPhp\Cache\Cacheable;
11
use TusPhp\Exception\FileException;
12
use TusPhp\Exception\ConnectionException;
13
use TusPhp\Exception\OutOfRangeException;
14
use Illuminate\Http\Request as HttpRequest;
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 int 460 Checksum Mismatch */
36
    const HTTP_CHECKSUM_MISMATCH = 460;
37
38
    /** @const string Default checksum algorithm */
39
    const DEFAULT_CHECKSUM_ALGORITHM = 'sha256';
40
41
    /** @const int 24 hours access control max age header */
42
    const HEADER_ACCESS_CONTROL_MAX_AGE = 86400;
43
44
    /** @var Request */
45
    protected $request;
46
47
    /** @var Response */
48
    protected $response;
49
50
    /** @var string */
51
    protected $uploadDir;
52
53
    /** @var string */
54
    protected $uploadKey;
55
56
    /**
57
     * TusServer constructor.
58
     *
59
     * @param Cacheable|string $cacheAdapter
60
     */
61 3
    public function __construct($cacheAdapter = 'file')
62
    {
63 3
        $this->request   = new Request;
64 3
        $this->response  = new Response;
65 3
        $this->uploadDir = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'uploads';
66
67 3
        $this->setCache($cacheAdapter);
68 3
    }
69
70
    /**
71
     * Set upload dir.
72
     *
73
     * @param string $path
74
     *
75
     * @return void
76
     */
77 2
    public function setUploadDir(string $path)
78
    {
79 2
        $this->uploadDir = $path;
80 2
    }
81
82
    /**
83
     * Get upload dir.
84
     *
85
     * @return string
86
     */
87 1
    public function getUploadDir() : string
88
    {
89 1
        return $this->uploadDir;
90
    }
91
92
    /**
93
     * Get request.
94
     *
95
     * @return Request
96
     */
97 1
    public function getRequest() : Request
98
    {
99 1
        return $this->request;
100
    }
101
102
    /**
103
     * Get request.
104
     *
105
     * @return Response
106
     */
107 1
    public function getResponse() : Response
108
    {
109 1
        return $this->response;
110
    }
111
112
    /**
113
     * Get file checksum.
114
     *
115
     * @param string $filePath
116
     *
117
     * @return string
118
     */
119 1
    public function getServerChecksum(string $filePath)
120
    {
121 1
        return hash_file($this->getChecksumAlgorithm(), $filePath);
122
    }
123
124
    /**
125
     * Get checksum algorithm.
126
     *
127
     * @return string|null
128
     */
129 1
    public function getChecksumAlgorithm()
130
    {
131 1
        $checksumHeader = $this->getRequest()->header('Upload-Checksum');
132
133 1
        if (empty($checksumHeader)) {
134 1
            return self::DEFAULT_CHECKSUM_ALGORITHM;
135
        }
136
137 1
        list($checksumAlgorithm) = explode(' ', $checksumHeader);
138
139 1
        return $checksumAlgorithm;
140
    }
141
142
    /**
143
     * Set upload key.
144
     *
145
     * @param string $key
146
     *
147
     * @return Server
148
     */
149 1
    public function setUploadKey(string $key) : self
150
    {
151 1
        $this->uploadKey = $key;
152
153 1
        return $this;
154
    }
155
156
    /**
157
     * Get upload key from header.
158
     *
159
     * @return string|HttpResponse
160
     */
161 4
    public function getUploadKey()
162
    {
163 4
        if ( ! empty($this->uploadKey)) {
164 1
            return $this->uploadKey;
165
        }
166
167 3
        $key = $this->getRequest()->header('Upload-Key') ?? Uuid::uuid4()->toString();
168
169 3
        if (empty($key)) {
170 1
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
171
        }
172
173 2
        $this->uploadKey = $key;
174
175 2
        return $this->uploadKey;
176
    }
177
178
    /**
179
     * Handle all HTTP request.
180
     *
181
     * @return null|HttpResponse
182
     */
183 2
    public function serve()
184
    {
185 2
        $requestMethod    = $this->getRequest()->method();
186 2
        $allowedHttpVerbs = $this->getRequest()->allowedHttpVerbs();
187
188
        $globalHeaders = [
189 2
            'Access-Control-Allow-Origin' => $this->request->header('Origin'),
190 2
            'Access-Control-Allow-Methods' => implode(',', $allowedHttpVerbs),
191 2
            'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Upload-Key, Upload-Checksum, Upload-Length, Upload-Offset, Tus-Resumable, Location, Upload-Metadata',
192 2
            'Access-Control-Max-Age' => self::HEADER_ACCESS_CONTROL_MAX_AGE,
193 2
            'Access-Control-Expose-Headers' => 'Upload-Key, Upload-Checksum, Upload-Length, Upload-Offset, Upload-Metadata, Location',
194
        ];
195
196 2
        if (HttpRequest::METHOD_OPTIONS !== $requestMethod) {
197 2
            $globalHeaders['Tus-Resumable'] = self::TUS_PROTOCOL_VERSION;
198
        }
199
200 2
        $this->getResponse()->setHeaders($globalHeaders);
201
202 2
        if ( ! in_array($requestMethod, $allowedHttpVerbs)) {
203 1
            return $this->response->send(null, HttpResponse::HTTP_METHOD_NOT_ALLOWED);
204
        }
205
206 1
        $method = 'handle' . ucfirst(strtolower($requestMethod));
207
208 1
        $this->{$method}();
209
210 1
        $this->exit();
211 1
    }
212
213
    /**
214
     * Exit from current php process.
215
     *
216
     * @codeCoverageIgnore
217
     */
218
    protected function exit()
219
    {
220
        exit(0);
221
    }
222
223
    /**
224
     * Handle OPTIONS request.
225
     *
226
     * @return HttpResponse
227
     */
228 1
    protected function handleOptions() : HttpResponse
229
    {
230 1
        return $this->response->send(
231 1
            null,
232 1
            HttpResponse::HTTP_OK,
233
            [
234 1
                'Allow' => implode(',', $this->request->allowedHttpVerbs()),
235 1
                'Tus-Version' => self::TUS_PROTOCOL_VERSION,
236 1
                'Tus-Extension' => implode(',', [
237 1
                    self::TUS_EXTENSION_CREATION,
238 1
                    self::TUS_EXTENSION_TERMINATION,
239 1
                    self::TUS_EXTENSION_CHECKSUM,
240 1
                    self::TUS_EXTENSION_EXPIRATION,
241 1
                    self::TUS_EXTENSION_CONCATENATION,
242
                ]),
243 1
                'Tus-Checksum-Algorithm' => $this->getSupportedHashAlgorithms(),
244
            ]
245
        );
246
    }
247
248
    /**
249
     * Handle HEAD request.
250
     *
251
     * @return HttpResponse
252
     */
253 5
    protected function handleHead() : HttpResponse
254
    {
255 5
        $key = $this->request->key();
256
257 5
        if ( ! $fileMeta = $this->cache->get($key)) {
258 1
            return $this->response->send(null, HttpResponse::HTTP_NOT_FOUND);
259
        }
260
261 4
        $offset = $fileMeta['offset'] ?? false;
262
263 4
        if (false === $offset) {
264 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
265
        }
266
267 3
        return $this->response->send(null, HttpResponse::HTTP_OK, $this->getHeadersForHeadRequest($fileMeta));
268
    }
269
270
    /**
271
     * Handle POST request.
272
     *
273
     * @return HttpResponse
274
     */
275 4
    protected function handlePost() : HttpResponse
276
    {
277 4
        $fileName   = $this->getRequest()->extractFileName();
278 4
        $uploadType = self::UPLOAD_TYPE_NORMAL;
279
280 4
        if (empty($fileName)) {
281 1
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
282
        }
283
284 3
        $uploadKey = $this->getUploadKey();
285 3
        $filePath  = $this->uploadDir . DIRECTORY_SEPARATOR . $fileName;
286
287 3
        if ($this->getRequest()->isFinal()) {
288 1
            return $this->handleConcatenation($fileName, $filePath);
289
        }
290
291 2
        if ($this->getRequest()->isPartial()) {
292 1
            $filePath   = $this->getPathForPartialUpload($uploadKey) . $fileName;
293 1
            $uploadType = self::UPLOAD_TYPE_PARTIAL;
294
        }
295
296 2
        $checksum = $this->getClientChecksum();
297 2
        $location = $location = $this->getRequest()->url() . $this->getApiPath() . '/' . $uploadKey;
0 ignored issues
show
Unused Code introduced by
The assignment to $location is dead and can be removed.
Loading history...
298
299 2
        $file = $this->buildFile([
300 2
            'name' => $fileName,
301 2
            'offset' => 0,
302 2
            'size' => $this->getRequest()->header('Upload-Length'),
303 2
            'file_path' => $filePath,
304 2
            'location' => $location,
305 2
        ])->setChecksum($checksum);
306
307 2
        $this->cache->set($uploadKey, $file->details() + ['upload_type' => $uploadType]);
308
309 2
        return $this->response->send(
310 2
            ['data' => ['checksum' => $checksum]],
311 2
            HttpResponse::HTTP_CREATED,
312
            [
313 2
                'Location' => $location,
314 2
                'Upload-Expires' => $this->cache->get($uploadKey)['expires_at'],
315
            ]
316
        );
317
    }
318
319
    /**
320
     * Handle file concatenation.
321
     *
322
     * @param string $fileName
323
     * @param string $filePath
324
     *
325
     * @return HttpResponse
326
     */
327 2
    protected function handleConcatenation(string $fileName, string $filePath) : HttpResponse
328
    {
329 2
        $partials  = $this->getRequest()->extractPartials();
330 2
        $uploadKey = $this->getUploadKey();
331 2
        $files     = $this->getPartialsMeta($partials);
332 2
        $filePaths = array_column($files, 'file_path');
333 2
        $location  = $this->getRequest()->url() . $this->getApiPath() . '/' . $uploadKey;
334
335 2
        $file = $this->buildFile([
336 2
            'name' => $fileName,
337 2
            'offset' => 0,
338 2
            'size' => 0,
339 2
            'file_path' => $filePath,
340 2
            'location' => $location,
341 2
        ])->setFilePath($filePath);
342
343 2
        $file->setOffset($file->merge($files));
344
345
        // Verify checksum.
346 2
        $checksum = $this->getServerChecksum($filePath);
347
348 2
        if ($checksum !== $this->getClientChecksum()) {
349 1
            return $this->response->send(null, self::HTTP_CHECKSUM_MISMATCH);
350
        }
351
352 1
        $this->cache->set($uploadKey, $file->details() + ['upload_type' => self::UPLOAD_TYPE_FINAL]);
353
354
        // Cleanup.
355 1
        if ($file->delete($filePaths, true)) {
356 1
            $this->cache->deleteAll($partials);
357
        }
358
359 1
        return $this->response->send(
360 1
            ['data' => ['checksum' => $checksum]],
361 1
            HttpResponse::HTTP_CREATED,
362
            [
363 1
                'Location' => $location,
364
            ]
365
        );
366
    }
367
368
    /**
369
     * Handle PATCH request.
370
     *
371
     * @return HttpResponse
372
     */
373 7
    protected function handlePatch() : HttpResponse
374
    {
375 7
        $uploadKey = $this->request->key();
376
377 7
        if ( ! $meta = $this->cache->get($uploadKey)) {
378 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
379
        }
380
381 6
        if (self::UPLOAD_TYPE_FINAL === $meta['upload_type']) {
382 1
            return $this->response->send(null, HttpResponse::HTTP_FORBIDDEN);
383
        }
384
385 5
        $file     = $this->buildFile($meta);
386 5
        $checksum = $meta['checksum'];
387
388
        try {
389 5
            $fileSize = $file->getFileSize();
390 5
            $offset   = $file->setKey($uploadKey)->setChecksum($checksum)->upload($fileSize);
391
392
            // If upload is done, verify checksum.
393 2
            if ($offset === $fileSize && ! empty($checksum) && $checksum !== $this->getServerChecksum($meta['file_path'])) {
394 2
                return $this->response->send(null, self::HTTP_CHECKSUM_MISMATCH);
395
            }
396 3
        } catch (FileException $e) {
397 1
            return $this->response->send($e->getMessage(), HttpResponse::HTTP_UNPROCESSABLE_ENTITY);
398 2
        } catch (OutOfRangeException $e) {
399 1
            return $this->response->send(null, HttpResponse::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE);
400 1
        } catch (ConnectionException $e) {
401 1
            return $this->response->send(null, HttpResponse::HTTP_CONTINUE);
402
        }
403
404 1
        return $this->response->send(null, HttpResponse::HTTP_NO_CONTENT, [
405 1
            'Upload-Expires' => $this->cache->get($uploadKey)['expires_at'],
406 1
            'Upload-Offset' => $offset,
407
        ]);
408
    }
409
410
    /**
411
     * Handle GET request.
412
     *
413
     * @return BinaryFileResponse|HttpResponse
414
     */
415 4
    protected function handleGet()
416
    {
417 4
        $key = $this->request->key();
418
419 4
        if (empty($key)) {
420 1
            return $this->response->send('400 bad request.', HttpResponse::HTTP_BAD_REQUEST);
421
        }
422
423 3
        if ( ! $fileMeta = $this->cache->get($key)) {
424 1
            return $this->response->send('404 upload not found.', HttpResponse::HTTP_NOT_FOUND);
425
        }
426
427 2
        $resource = $fileMeta['file_path'] ?? null;
428 2
        $fileName = $fileMeta['name'] ?? null;
429
430 2
        if ( ! $resource || ! file_exists($resource)) {
431 1
            return $this->response->send('404 upload not found.', HttpResponse::HTTP_NOT_FOUND);
432
        }
433
434 1
        return $this->response->download($resource, $fileName);
435
    }
436
437
    /**
438
     * Handle DELETE request.
439
     *
440
     * @return HttpResponse
441
     */
442 3
    protected function handleDelete() : HttpResponse
443
    {
444 3
        $key      = $this->request->key();
445 3
        $fileMeta = $this->cache->get($key);
446 3
        $resource = $fileMeta['file_path'] ?? null;
447
448 3
        if ( ! $resource) {
449 1
            return $this->response->send(null, HttpResponse::HTTP_NOT_FOUND);
450
        }
451
452 2
        $isDeleted = $this->cache->delete($key);
453
454 2
        if ( ! $isDeleted || ! file_exists($resource)) {
455 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
456
        }
457
458 1
        unlink($resource);
459
460 1
        return $this->response->send(null, HttpResponse::HTTP_NO_CONTENT, [
461 1
            'Tus-Extension' => self::TUS_EXTENSION_TERMINATION,
462
        ]);
463
    }
464
465
    /**
466
     * Get required headers for head request.
467
     *
468
     * @param array $fileMeta
469
     *
470
     * @return array
471
     */
472 4
    protected function getHeadersForHeadRequest(array $fileMeta) : array
473
    {
474
        $headers = [
475 4
            'Upload-Length' => (int) $fileMeta['size'],
476 4
            'Upload-Offset' => (int) $fileMeta['offset'],
477 4
            'Cache-Control' => 'no-store',
478
        ];
479
480 4
        if (self::UPLOAD_TYPE_FINAL === $fileMeta['upload_type'] && $fileMeta['size'] !== $fileMeta['offset']) {
481 2
            unset($headers['Upload-Offset']);
482
        }
483
484 4
        if (self::UPLOAD_TYPE_NORMAL !== $fileMeta['upload_type']) {
485 3
            $headers += ['Upload-Concat' => $fileMeta['upload_type']];
486
        }
487
488 4
        return $headers;
489
    }
490
491
    /**
492
     * Build file object.
493
     *
494
     * @param array $meta
495
     *
496
     * @return File
497
     */
498 1
    protected function buildFile(array $meta) : File
499
    {
500 1
        $file = new File($meta['name'], $this->cache);
501
502 1
        if (array_key_exists('offset', $meta)) {
503 1
            $file->setMeta($meta['offset'], $meta['size'], $meta['file_path'], $meta['location']);
504
        }
505
506 1
        return $file;
507
    }
508
509
    /**
510
     * Get list of supported hash algorithms.
511
     *
512
     * @return string
513
     */
514 1
    protected function getSupportedHashAlgorithms()
515
    {
516 1
        $supportedAlgorithms = hash_algos();
517
518 1
        $algorithms = [];
519 1
        foreach ($supportedAlgorithms as $hashAlgo) {
520 1
            if (false !== strpos($hashAlgo, ',')) {
521 1
                $algorithms[] = "'{$hashAlgo}'";
522
            } else {
523 1
                $algorithms[] = $hashAlgo;
524
            }
525
        }
526
527 1
        return implode(',', $algorithms);
528
    }
529
530
    /**
531
     * Verify and get upload checksum from header.
532
     *
533
     * @return string|HttpResponse
534
     */
535 4
    protected function getClientChecksum()
536
    {
537 4
        $checksumHeader = $this->getRequest()->header('Upload-Checksum');
538
539 4
        if (empty($checksumHeader)) {
540 1
            return '';
541
        }
542
543 3
        list($checksumAlgorithm, $checksum) = explode(' ', $checksumHeader);
544
545 3
        $checksum = base64_decode($checksum);
546
547 3
        if ( ! in_array($checksumAlgorithm, hash_algos()) || false === $checksum) {
548 2
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
549
        }
550
551 1
        return $checksum;
552
    }
553
554
    /**
555
     * Get expired but incomplete uploads.
556
     *
557
     * @param array|null $contents
558
     *
559
     * @return bool
560
     */
561 3
    protected function isExpired($contents) : bool
562
    {
563 3
        $isExpired = empty($contents['expires_at']) || Carbon::parse($contents['expires_at'])->lt(Carbon::now());
564
565 3
        if ($isExpired && $contents['offset'] !== $contents['size']) {
566 3
            return true;
567
        }
568
569 2
        return false;
570
    }
571
572
    /**
573
     * Get path for partial upload.
574
     *
575
     * @param string $key
576
     *
577
     * @return string
578
     */
579 1
    protected function getPathForPartialUpload(string $key) : string
580
    {
581 1
        list($actualKey) = explode(self::PARTIAL_UPLOAD_NAME_SEPARATOR, $key);
582
583 1
        $path = $this->uploadDir . DIRECTORY_SEPARATOR . $actualKey . DIRECTORY_SEPARATOR;
584
585 1
        if ( ! file_exists($path)) {
586 1
            mkdir($path);
587
        }
588
589 1
        return $path;
590
    }
591
592
    /**
593
     * Get metadata of partials.
594
     *
595
     * @param array $partials
596
     *
597
     * @return array
598
     */
599 3
    protected function getPartialsMeta(array $partials)
600
    {
601 3
        $files = [];
602
603 3
        foreach ($partials as $partial) {
604 3
            $fileMeta = $this->getCache()->get($partial);
605
606 3
            $files[] = $fileMeta;
607
        }
608
609 3
        return $files;
610
    }
611
612
    /**
613
     * Delete expired resources.
614
     *
615
     * @return array
616
     */
617 2
    public function handleExpiration()
618
    {
619 2
        $deleted   = [];
620 2
        $cacheKeys = $this->cache->keys();
621
622 2
        foreach ($cacheKeys as $key) {
623 2
            $fileMeta = $this->cache->get($key, true);
624
625 2
            if ( ! $this->isExpired($fileMeta)) {
626 1
                continue;
627
            }
628
629 2
            if ( ! $this->cache->delete($key)) {
630 1
                continue;
631
            }
632
633 1
            if (is_writable($fileMeta['file_path'])) {
634 1
                unlink($fileMeta['file_path']);
635
            }
636
637 1
            $deleted[] = $fileMeta;
638
        }
639
640 2
        return $deleted;
641
    }
642
643
    /**
644
     * No other methods are allowed.
645
     *
646
     * @param string $method
647
     * @param array  $params
648
     *
649
     * @return HttpResponse|BinaryFileResponse
650
     */
651 1
    public function __call(string $method, array $params)
652
    {
653 1
        return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
654
    }
655
}
656