Completed
Pull Request — master (#11)
by Ankit
02:37
created

Server::getChecksumAlgorithm()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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