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

Server::getPathForPartialUpload()   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 1
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 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 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 6
    protected function handlePatch() : HttpResponse
333
    {
334 6
        $checksum = $this->request->checksum();
335
336 6
        if ( ! $this->cache->get($checksum)) {
337 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
338
        }
339
340 5
        $meta = $this->cache->get($checksum);
341 5
        $file = $this->buildFile($meta);
342
343
        try {
344 5
            $fileSize = $file->getFileSize();
345 5
            $offset   = $file->setChecksum($checksum)->upload($fileSize);
346
347
            // If upload is done, verify checksum.
348 2
            if ($offset === $fileSize && $checksum !== $this->getUploadChecksum()) {
349 2
                return $this->response->send(null, self::HTTP_CHECKSUM_MISMATCH);
350
            }
351 3
        } catch (FileException $e) {
352 1
            return $this->response->send($e->getMessage(), HttpResponse::HTTP_UNPROCESSABLE_ENTITY);
353 2
        } catch (OutOfRangeException $e) {
354 1
            return $this->response->send(null, HttpResponse::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE);
355 1
        } catch (ConnectionException $e) {
356 1
            return $this->response->send(null, HttpResponse::HTTP_CONTINUE);
357
        }
358
359 1
        return $this->response->send(null, HttpResponse::HTTP_NO_CONTENT, [
360 1
            'Upload-Expires' => $this->cache->get($checksum)['expires_at'],
361 1
            'Upload-Offset' => $offset,
362 1
            'Tus-Resumable' => self::TUS_PROTOCOL_VERSION,
363
        ]);
364
    }
365
366
    /**
367
     * Handle GET request.
368
     *
369
     * @return BinaryFileResponse|HttpResponse
370
     */
371 4
    protected function handleGet()
372
    {
373 4
        $checksum = $this->request->checksum();
374
375 4
        if (empty($checksum)) {
376 1
            return $this->response->send('400 bad request.', HttpResponse::HTTP_BAD_REQUEST);
377
        }
378
379 3
        $fileMeta = $this->cache->get($checksum);
380
381 3
        if ( ! $fileMeta) {
382 1
            return $this->response->send('404 upload not found.', HttpResponse::HTTP_NOT_FOUND);
383
        }
384
385 2
        $resource = $fileMeta['file_path'] ?? null;
386 2
        $fileName = $fileMeta['name'] ?? null;
387
388 2
        if ( ! $resource || ! file_exists($resource)) {
389 1
            return $this->response->send('404 upload not found.', HttpResponse::HTTP_NOT_FOUND);
390
        }
391
392 1
        return $this->response->download($resource, $fileName);
393
    }
394
395
    /**
396
     * Handle DELETE request.
397
     *
398
     * @return HttpResponse
399
     */
400 3
    protected function handleDelete() : HttpResponse
401
    {
402 3
        $checksum = $this->request->checksum();
403 3
        $fileMeta = $this->cache->get($checksum);
404 3
        $resource = $fileMeta['file_path'] ?? null;
405
406 3
        if ( ! $resource) {
407 1
            return $this->response->send(null, HttpResponse::HTTP_NOT_FOUND);
408
        }
409
410 2
        $isDeleted = $this->cache->delete($checksum);
411
412 2
        if ( ! $isDeleted || ! file_exists($resource)) {
413 1
            return $this->response->send(null, HttpResponse::HTTP_GONE);
414
        }
415
416 1
        unlink($resource);
417
418 1
        return $this->response->send(null, HttpResponse::HTTP_NO_CONTENT, [
419 1
            'Tus-Resumable' => self::TUS_PROTOCOL_VERSION,
420 1
            'Tus-Extension' => self::TUS_EXTENSION_TERMINATION,
421
        ]);
422
    }
423
424
    /**
425
     * Build file object.
426
     *
427
     * @param array $meta
428
     *
429
     * @return File
430
     */
431 1
    protected function buildFile(array $meta) : File
432
    {
433 1
        $file = new File($meta['name'], $this->cache);
434
435 1
        if (array_key_exists('offset', $meta)) {
436 1
            $file->setMeta($meta['offset'], $meta['size'], $meta['file_path'], $meta['location']);
437
        }
438
439 1
        return $file;
440
    }
441
442
    /**
443
     * Get list of supported hash algorithms.
444
     *
445
     * @return string
446
     */
447 1
    protected function getSupportedHashAlgorithms()
448
    {
449 1
        $supportedAlgorithms = hash_algos();
450
451 1
        $algorithms = [];
452 1
        foreach ($supportedAlgorithms as $hashAlgo) {
453 1
            if (false !== strpos($hashAlgo, ',')) {
454 1
                $algorithms[] = "'{$hashAlgo}'";
455
            } else {
456 1
                $algorithms[] = $hashAlgo;
457
            }
458
        }
459
460 1
        return implode(',', $algorithms);
461
    }
462
463
    /**
464
     * Verify and get upload checksum from header.
465
     *
466
     * @return string|HttpResponse
467
     */
468 4
    protected function getUploadChecksum()
469
    {
470 4
        $checksumHeader = $this->getRequest()->header('Upload-Checksum');
471
472 4
        if (empty($checksumHeader)) {
473 1
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
474
        }
475
476 3
        list($checksumAlgorithm, $checksum) = explode(' ', $checksumHeader);
477
478 3
        $checksum = base64_decode($checksum);
479
480 3
        if ( ! in_array($checksumAlgorithm, hash_algos()) || false === $checksum) {
481 2
            return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
482
        }
483
484 1
        return $checksum;
485
    }
486
487
    /**
488
     * Get expired but incomplete uploads.
489
     *
490
     * @param array|null $contents
491
     *
492
     * @return bool
493
     */
494 3
    protected function isExpired($contents) : bool
495
    {
496 3
        $isExpired = empty($contents['expires_at']) || Carbon::parse($contents['expires_at'])->lt(Carbon::now());
497
498 3
        if ($isExpired && $contents['offset'] !== $contents['size']) {
499 3
            return true;
500
        }
501
502 2
        return false;
503
    }
504
505
    /**
506
     * Get path for partial upload.
507
     *
508
     * @param string $checksum
509
     *
510
     * @return string
511
     */
512 1
    protected function getPathForPartialUpload(string $checksum) : string
513
    {
514 1
        list($actualChecksum) = explode(self::PARTIAL_UPLOAD_NAME_SEPARATOR, $checksum);
515
516 1
        $path = $this->uploadDir . DIRECTORY_SEPARATOR . $actualChecksum . DIRECTORY_SEPARATOR;
517
518 1
        if ( ! file_exists($path)) {
519 1
            mkdir($path);
520
        }
521
522 1
        return $path;
523
    }
524
525
    /**
526
     * Delete expired resources.
527
     *
528
     * @return array
529
     */
530 2
    public function handleExpiration()
531
    {
532 2
        $deleted   = [];
533 2
        $cacheKeys = $this->cache->keys();
534
535 2
        foreach ($cacheKeys as $key) {
536 2
            $fileMeta = $this->cache->get($key, true);
537
538 2
            if ( ! $this->isExpired($fileMeta)) {
539 1
                continue;
540
            }
541
542 2
            $cacheDeleted = $this->cache->delete($key);
543
544 2
            if ( ! $cacheDeleted) {
545 1
                continue;
546
            }
547
548 1
            if (file_exists($fileMeta['file_path']) && is_writable($fileMeta['file_path'])) {
549 1
                unlink($fileMeta['file_path']);
550
            }
551
552 1
            $deleted[] = $fileMeta;
553
        }
554
555 2
        return $deleted;
556
    }
557
558
    /**
559
     * No other methods are allowed.
560
     *
561
     * @param string $method
562
     * @param array  $params
563
     *
564
     * @return HttpResponse|BinaryFileResponse
565
     */
566 1
    public function __call(string $method, array $params)
567
    {
568 1
        return $this->response->send(null, HttpResponse::HTTP_BAD_REQUEST);
569
    }
570
}
571