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

Server::getSupportedHashAlgorithms()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 0
dl 0
loc 14
ccs 8
cts 8
cp 1
crap 3
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 Tus Creation Extension */
19
    const TUS_EXTENSION_CREATION = 'creation';
20
21
    /** @const Tus Termination Extension */
22
    const TUS_EXTENSION_TERMINATION = 'termination';
23
24
    /** @const Tus Checksum Extension */
25
    const TUS_EXTENSION_CHECKSUM = 'checksum';
26
27
    /** @const Tus Expiration Extension */
28
    const TUS_EXTENSION_EXPIRATION = 'expiration';
29
30
    /** @const Tus Concatenation Extension */
31
    const TUS_EXTENSION_CONCATENATION = 'concatenation';
32
33
    /** @const 460 Checksum Mismatch */
34
    const HTTP_CHECKSUM_MISMATCH = 460;
35
36
    /** @const 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 2
    public function setUploadDir(string $path)
70
    {
71 2
        $this->uploadDir = $path;
72 2
    }
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 3
    protected function handleHead() : HttpResponse
195
    {
196 3
        $checksum = $this->request->checksum();
197
198 3
        if ( ! $this->cache->get($checksum)) {
199 1
            return $this->response->send(null, HttpResponse::HTTP_NOT_FOUND);
200
        }
201
202 2
        $offset = $this->cache->get($checksum)['offset'] ?? false;
203
204 2
        if (false === $offset) {
205 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
206
        }
207
208 1
        return $this->response->send(null, HttpResponse::HTTP_OK, [
209 1
            'Upload-Offset' => (int) $offset,
210 1
            'Cache-Control' => 'no-store',
211 1
            'Tus-Resumable' => self::TUS_PROTOCOL_VERSION,
212
        ]);
213
    }
214
215
    /**
216
     * Handle POST request.
217
     *
218
     * @return HttpResponse
219
     */
220 4
    protected function handlePost() : HttpResponse
221
    {
222 4
        $fileName = $this->getRequest()->extractFileName();
223
224 4
        if (empty($fileName)) {
225 1
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
226
        }
227
228 3
        $checksum = $this->getUploadChecksum();
229 3
        $filePath = $this->uploadDir . DIRECTORY_SEPARATOR . $fileName;
230
231 3
        if ($this->getRequest()->isFinal()) {
232 1
            return $this->handleConcatenation($fileName, $filePath);
233
        }
234
235 2
        if ($this->getRequest()->isPartial()) {
236 1
            $filePath = $this->getPathForPartialUpload($checksum) . $fileName;
237
        }
238
239 2
        $location = $this->getRequest()->url() . '/' . basename($this->uploadDir) . '/' . $fileName;
240
241 2
        $file = $this->buildFile([
242 2
            'name' => $fileName,
243 2
            'offset' => 0,
244 2
            'size' => $this->getRequest()->header('Upload-Length'),
245 2
            'file_path' => $filePath,
246 2
            'location' => $location,
247 2
        ])->setChecksum($checksum);
248
249 2
        $this->cache->set($checksum, $file->details());
250
251 2
        return $this->response->send(
252 2
            ['data' => ['checksum' => $checksum]],
253 2
            HttpResponse::HTTP_CREATED,
254
            [
255 2
                'Location' => $location,
256 2
                'Upload-Expires' => $this->cache->get($checksum)['expires_at'],
257 2
                'Tus-Resumable' => self::TUS_PROTOCOL_VERSION,
258
            ]
259
        );
260
    }
261
262
    /**
263
     * Handle file concatenation.
264
     *
265
     * @param string $fileName
266
     * @param string $filePath
267
     *
268
     * @return HttpResponse
269
     */
270 2
    protected function handleConcatenation(string $fileName, string $filePath) : HttpResponse
271
    {
272 2
        $files     = [];
273 2
        $filePaths = [];
274 2
        $partials  = $this->getRequest()->extractPartials();
275 2
        $location  = $this->getRequest()->url() . '/' . basename($this->uploadDir) . '/' . $fileName;
276
277 2
        foreach ($partials as $partial) {
278 2
            $fileMeta = $this->getCache()->get($partial);
279
280 2
            $files[]     = $fileMeta;
281 2
            $filePaths[] = $fileMeta['file_path'];
282
        }
283
284 2
        $file = $this->buildFile([
285 2
            'name' => $fileName,
286 2
            'offset' => 0,
287 2
            'size' => 0,
288 2
            'file_path' => $filePath,
289 2
            'location' => $location,
290 2
        ])->setFilePath($filePath);
291
292 2
        $file->setOffset($file->merge($files));
293
294
        // Verify checksum.
295 2
        $checksum = $this->getChecksum($filePath);
296
297 2
        if ($checksum !== $this->getUploadChecksum()) {
298 1
            return $this->response->send(null, self::HTTP_CHECKSUM_MISMATCH);
299
        }
300
301 1
        $this->cache->set($checksum, $file->details());
302
303
        // Cleanup.
304 1
        if ($file->delete($filePaths, true)) {
305 1
            $this->cache->deleteAll($partials);
306
        }
307
308 1
        return $this->response->send(
309 1
            ['data' => ['checksum' => $checksum]],
310 1
            HttpResponse::HTTP_CREATED,
311
            [
312 1
                'Location' => $location,
313 1
                'Tus-Resumable' => self::TUS_PROTOCOL_VERSION,
314
            ]
315
        );
316
    }
317
318
    /**
319
     * Handle PATCH request.
320
     *
321
     * @return HttpResponse
322
     */
323 6
    protected function handlePatch() : HttpResponse
324
    {
325 6
        $checksum = $this->request->checksum();
326
327 6
        if ( ! $this->cache->get($checksum)) {
328 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
329
        }
330
331 5
        $meta = $this->cache->get($checksum);
332 5
        $file = $this->buildFile($meta);
333
334
        try {
335 5
            $fileSize = $file->getFileSize();
336 5
            $offset   = $file->setChecksum($checksum)->upload($fileSize);
337
338
            // If upload is done, verify checksum.
339 2
            if ($offset === $fileSize && $checksum !== $this->getUploadChecksum()) {
340 2
                return $this->response->send(null, self::HTTP_CHECKSUM_MISMATCH);
341
            }
342 3
        } catch (FileException $e) {
343 1
            return $this->response->send($e->getMessage(), HttpResponse::HTTP_UNPROCESSABLE_ENTITY);
344 2
        } catch (OutOfRangeException $e) {
345 1
            return $this->response->send(null, HttpResponse::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE);
346 1
        } catch (ConnectionException $e) {
347 1
            return $this->response->send(null, HttpResponse::HTTP_CONTINUE);
348
        }
349
350 1
        return $this->response->send(null, HttpResponse::HTTP_NO_CONTENT, [
351 1
            'Upload-Expires' => $this->cache->get($checksum)['expires_at'],
352 1
            'Upload-Offset' => $offset,
353 1
            'Tus-Resumable' => self::TUS_PROTOCOL_VERSION,
354
        ]);
355
    }
356
357
    /**
358
     * Handle GET request.
359
     *
360
     * @return BinaryFileResponse|HttpResponse
361
     */
362 4
    protected function handleGet()
363
    {
364 4
        $checksum = $this->request->checksum();
365
366 4
        if (empty($checksum)) {
367 1
            return $this->response->send('400 bad request.', HttpResponse::HTTP_BAD_REQUEST);
368
        }
369
370 3
        $fileMeta = $this->cache->get($checksum);
371
372 3
        if ( ! $fileMeta) {
373 1
            return $this->response->send('404 upload not found.', HttpResponse::HTTP_NOT_FOUND);
374
        }
375
376 2
        $resource = $fileMeta['file_path'] ?? null;
377 2
        $fileName = $fileMeta['name'] ?? null;
378
379 2
        if ( ! $resource || ! file_exists($resource)) {
380 1
            return $this->response->send('404 upload not found.', HttpResponse::HTTP_NOT_FOUND);
381
        }
382
383 1
        return $this->response->download($resource, $fileName);
384
    }
385
386
    /**
387
     * Handle DELETE request.
388
     *
389
     * @return HttpResponse
390
     */
391 3
    protected function handleDelete() : HttpResponse
392
    {
393 3
        $checksum = $this->request->checksum();
394 3
        $fileMeta = $this->cache->get($checksum);
395 3
        $resource = $fileMeta['file_path'] ?? null;
396
397 3
        if ( ! $resource) {
398 1
            return $this->response->send(null, HttpResponse::HTTP_NOT_FOUND);
399
        }
400
401 2
        $isDeleted = $this->cache->delete($checksum);
402
403 2
        if ( ! $isDeleted || ! file_exists($resource)) {
404 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
405
        }
406
407 1
        unlink($resource);
408
409 1
        return $this->response->send(null, HttpResponse::HTTP_NO_CONTENT, [
410 1
            'Tus-Resumable' => self::TUS_PROTOCOL_VERSION,
411 1
            'Tus-Extension' => self::TUS_EXTENSION_TERMINATION,
412
        ]);
413
    }
414
415
    /**
416
     * Build file object.
417
     *
418
     * @param array $meta
419
     *
420
     * @return File
421
     */
422 1
    protected function buildFile(array $meta) : File
423
    {
424 1
        $file = new File($meta['name'], $this->cache);
425
426 1
        if (array_key_exists('offset', $meta)) {
427 1
            $file->setMeta($meta['offset'], $meta['size'], $meta['file_path'], $meta['location']);
428
        }
429
430 1
        return $file;
431
    }
432
433
    /**
434
     * Get list of supported hash algorithms.
435
     *
436
     * @return string
437
     */
438 1
    protected function getSupportedHashAlgorithms()
439
    {
440 1
        $supportedAlgorithms = hash_algos();
441
442 1
        $algorithms = [];
443 1
        foreach ($supportedAlgorithms as $hashAlgo) {
444 1
            if (false !== strpos($hashAlgo, ',')) {
445 1
                $algorithms[] = "'{$hashAlgo}'";
446
            } else {
447 1
                $algorithms[] = $hashAlgo;
448
            }
449
        }
450
451 1
        return implode(',', $algorithms);
452
    }
453
454
    /**
455
     * Verify and get upload checksum from header.
456
     *
457
     * @return string|HttpResponse
458
     */
459 4
    protected function getUploadChecksum()
460
    {
461 4
        $checksumHeader = $this->getRequest()->header('Upload-Checksum');
462
463 4
        if (empty($checksumHeader)) {
464 1
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
465
        }
466
467 3
        list($checksumAlgorithm, $checksum) = explode(' ', $checksumHeader);
468
469 3
        $checksum = base64_decode($checksum);
470
471 3
        if ( ! in_array($checksumAlgorithm, hash_algos()) || false === $checksum) {
472 2
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
473
        }
474
475 1
        return $checksum;
476
    }
477
478
    /**
479
     * Get expired but incomplete uploads.
480
     *
481
     * @param array|null $contents
482
     *
483
     * @return bool
484
     */
485 3
    protected function isExpired($contents) : bool
486
    {
487 3
        $isExpired = empty($contents['expires_at']) || Carbon::parse($contents['expires_at'])->lt(Carbon::now());
488
489 3
        if ($isExpired && $contents['offset'] !== $contents['size']) {
490 3
            return true;
491
        }
492
493 2
        return false;
494
    }
495
496
    /**
497
     * Get path for partial upload.
498
     *
499
     * @param string $checksum
500
     *
501
     * @return string
502
     */
503 1
    protected function getPathForPartialUpload(string $checksum) : string
504
    {
505 1
        list($actualChecksum) = explode(self::PARTIAL_UPLOAD_NAME_SEPARATOR, $checksum);
506
507 1
        $path = $this->uploadDir . DIRECTORY_SEPARATOR . $actualChecksum . DIRECTORY_SEPARATOR;
508
509 1
        if ( ! file_exists($path)) {
510 1
            mkdir($path);
511
        }
512
513 1
        return $path;
514
    }
515
516
    /**
517
     * Delete expired resources.
518
     *
519
     * @return array
520
     */
521 2
    public function handleExpiration()
522
    {
523 2
        $deleted   = [];
524 2
        $cacheKeys = $this->cache->keys();
525
526 2
        foreach ($cacheKeys as $key) {
527 2
            $fileMeta = $this->cache->get($key, true);
528
529 2
            if ( ! $this->isExpired($fileMeta)) {
530 1
                continue;
531
            }
532
533 2
            $cacheDeleted = $this->cache->delete($key);
534
535 2
            if ( ! $cacheDeleted) {
536 1
                continue;
537
            }
538
539 1
            if (file_exists($fileMeta['file_path']) && is_writable($fileMeta['file_path'])) {
540 1
                unlink($fileMeta['file_path']);
541
            }
542
543 1
            $deleted[] = $fileMeta;
544
        }
545
546 2
        return $deleted;
547
    }
548
549
    /**
550
     * No other methods are allowed.
551
     *
552
     * @param string $method
553
     * @param array  $params
554
     *
555
     * @return HttpResponse|BinaryFileResponse
556
     */
557 1
    public function __call(string $method, array $params)
558
    {
559 1
        return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
560
    }
561
}
562