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

Server::getChecksum()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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