Passed
Pull Request — master (#4)
by Ankit
06:17 queued 43s
created

Server::getSupportedHashAlgorithms()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

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