GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#39)
by Mitja
02:23
created

Client::uploadChunked()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.439
c 0
b 0
f 0
cc 6
eloc 15
nc 8
nop 4
1
<?php
2
3
namespace Spatie\Dropbox;
4
5
use Exception;
6
use GuzzleHttp\Psr7;
7
use GuzzleHttp\Psr7\StreamWrapper;
8
use Psr\Http\Message\StreamInterface;
9
use GuzzleHttp\Client as GuzzleClient;
10
use Psr\Http\Message\ResponseInterface;
11
use GuzzleHttp\Exception\ClientException;
12
use Spatie\Dropbox\Exceptions\BadRequest;
13
use GuzzleHttp\Exception\RequestException;
14
15
class Client
16
{
17
    const THUMBNAIL_FORMAT_JPEG = 'jpeg';
18
    const THUMBNAIL_FORMAT_PNG = 'png';
19
20
    const THUMBNAIL_SIZE_XS = 'w32h32';
21
    const THUMBNAIL_SIZE_S = 'w64h64';
22
    const THUMBNAIL_SIZE_M = 'w128h128';
23
    const THUMBNAIL_SIZE_L = 'w640h480';
24
    const THUMBNAIL_SIZE_XL = 'w1024h768';
25
26
    const MAX_CHUNK_SIZE = 1024 * 1024 * 150;
27
28
    const UPLOAD_SESSION_START = 0;
29
    const UPLOAD_SESSION_APPEND = 1;
30
31
    /** @var string */
32
    protected $accessToken;
33
34
    /** @var \GuzzleHttp\Client */
35
    protected $client;
36
37
    /** @var int */
38
    protected $maxChunkSize;
39
40
    /** @var int */
41
    protected $maxUploadChunkRetries;
42
43
    /**
44
     * @param string            $accessToken
45
     * @param GuzzleClient|null $client
46
     * @param int               $maxChunkSize Set max chunk size per request (determines when to switch from "one shot upload" to upload session and defines chunk size for uploads via session).
47
     * @param int               $maxUploadChunkRetries How many times to retry an upload session start or append after RequestException.
48
     */
49
    public function __construct(string $accessToken, GuzzleClient $client = null, int $maxChunkSize = self::MAX_CHUNK_SIZE, int $maxUploadChunkRetries = 0)
50
    {
51
        $this->accessToken = $accessToken;
52
53
        $this->client = $client ?? new GuzzleClient([
54
                'headers' => [
55
                    'Authorization' => "Bearer {$this->accessToken}",
56
                ],
57
            ]);
58
59
        $this->maxChunkSize = ($maxChunkSize < self::MAX_CHUNK_SIZE ? ($maxChunkSize > 1 ? $maxChunkSize : 1) : self::MAX_CHUNK_SIZE);
60
        $this->maxUploadChunkRetries = $maxUploadChunkRetries;
61
    }
62
63
    /**
64
     * Copy a file or folder to a different location in the user's Dropbox.
65
     *
66
     * If the source path is a folder all its contents will be copied.
67
     *
68
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy_v2
69
     */
70 View Code Duplication
    public function copy(string $fromPath, string $toPath): array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
71
    {
72
        $parameters = [
73
            'from_path' => $this->normalizePath($fromPath),
74
            'to_path' => $this->normalizePath($toPath),
75
        ];
76
77
        return $this->rpcEndpointRequest('files/copy_v2', $parameters);
78
    }
79
80
    /**
81
     * Create a folder at a given path.
82
     *
83
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-create_folder
84
     */
85
    public function createFolder(string $path): array
86
    {
87
        $parameters = [
88
            'path' => $this->normalizePath($path),
89
        ];
90
91
        $object = $this->rpcEndpointRequest('files/create_folder', $parameters);
92
93
        $object['.tag'] = 'folder';
94
95
        return $object;
96
    }
97
98
    /**
99
     * Create a shared link with custom settings.
100
     *
101
     * If no settings are given then the default visibility is RequestedVisibility.public.
102
     * The resolved visibility, though, may depend on other aspects such as team and
103
     * shared folder settings). Only for paid users.
104
     *
105
     * @link https://www.dropbox.com/developers/documentation/http/documentation#sharing-create_shared_link_with_settings
106
     */
107 View Code Duplication
    public function createSharedLinkWithSettings(string $path, array $settings = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
108
    {
109
        $parameters = [
110
            'path' => $this->normalizePath($path),
111
            'settings' => $settings,
112
        ];
113
114
        return $this->rpcEndpointRequest('sharing/create_shared_link_with_settings', $parameters);
115
    }
116
117
    /**
118
     * List shared links.
119
     *
120
     * For empty path returns a list of all shared links. For non-empty path
121
     * returns a list of all shared links with access to the given path.
122
     *
123
     * If direct_only is set true, only direct links to the path will be returned, otherwise
124
     * it may return link to the path itself and parent folders as described on docs.
125
     *
126
     * @link https://www.dropbox.com/developers/documentation/http/documentation#sharing-list_shared_links
127
     */
128
    public function listSharedLinks(string $path = null, bool $direct_only = false, string $cursor = null): array
129
    {
130
        $parameters = [
131
            'path' => $path ? $this->normalizePath($path) : null,
132
            'cursor' => $cursor,
133
            'direct_only' => $direct_only,
134
        ];
135
136
        $body = $this->rpcEndpointRequest('sharing/list_shared_links', $parameters);
137
138
        return $body['links'];
139
    }
140
141
    /**
142
     * Delete the file or folder at a given path.
143
     *
144
     * If the path is a folder, all its contents will be deleted too.
145
     * A successful response indicates that the file or folder was deleted.
146
     *
147
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-delete
148
     */
149
    public function delete(string $path): array
150
    {
151
        $parameters = [
152
            'path' => $this->normalizePath($path),
153
        ];
154
155
        return $this->rpcEndpointRequest('files/delete', $parameters);
156
    }
157
158
    /**
159
     * Download a file from a user's Dropbox.
160
     *
161
     * @param string $path
162
     *
163
     * @return resource
164
     *
165
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-download
166
     */
167
    public function download(string $path)
168
    {
169
        $arguments = [
170
            'path' => $this->normalizePath($path),
171
        ];
172
173
        $response = $this->contentEndpointRequest('files/download', $arguments);
174
175
        return StreamWrapper::getResource($response->getBody());
176
    }
177
178
    /**
179
     * Returns the metadata for a file or folder.
180
     *
181
     * Note: Metadata for the root folder is unsupported.
182
     *
183
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_metadata
184
     */
185
    public function getMetadata(string $path): array
186
    {
187
        $parameters = [
188
            'path' => $this->normalizePath($path),
189
        ];
190
191
        return $this->rpcEndpointRequest('files/get_metadata', $parameters);
192
    }
193
194
    /**
195
     * Get a temporary link to stream content of a file.
196
     *
197
     * This link will expire in four hours and afterwards you will get 410 Gone.
198
     * Content-Type of the link is determined automatically by the file's mime type.
199
     *
200
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_temporary_link
201
     */
202 View Code Duplication
    public function getTemporaryLink(string $path): string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
203
    {
204
        $parameters = [
205
            'path' => $this->normalizePath($path),
206
        ];
207
208
        $body = $this->rpcEndpointRequest('files/get_temporary_link', $parameters);
209
210
        return $body['link'];
211
    }
212
213
    /**
214
     * Get a thumbnail for an image.
215
     *
216
     * This method currently supports files with the following file extensions:
217
     * jpg, jpeg, png, tiff, tif, gif and bmp.
218
     *
219
     * Photos that are larger than 20MB in size won't be converted to a thumbnail.
220
     *
221
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_thumbnail
222
     */
223
    public function getThumbnail(string $path, string $format = 'jpeg', string $size = 'w64h64'): string
224
    {
225
        $arguments = [
226
            'path' => $this->normalizePath($path),
227
            'format' => $format,
228
            'size' => $size,
229
        ];
230
231
        $response = $this->contentEndpointRequest('files/get_thumbnail', $arguments);
232
233
        return (string) $response->getBody();
234
    }
235
236
    /**
237
     * Starts returning the contents of a folder.
238
     *
239
     * If the result's ListFolderResult.has_more field is true, call
240
     * list_folder/continue with the returned ListFolderResult.cursor to retrieve more entries.
241
     *
242
     * Note: auth.RateLimitError may be returned if multiple list_folder or list_folder/continue calls
243
     * with same parameters are made simultaneously by same API app for same user. If your app implements
244
     * retry logic, please hold off the retry until the previous request finishes.
245
     *
246
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder
247
     */
248 View Code Duplication
    public function listFolder(string $path = '', bool $recursive = false): array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
249
    {
250
        $parameters = [
251
            'path' => $this->normalizePath($path),
252
            'recursive' => $recursive,
253
        ];
254
255
        return $this->rpcEndpointRequest('files/list_folder', $parameters);
256
    }
257
258
    /**
259
     * Once a cursor has been retrieved from list_folder, use this to paginate through all files and
260
     * retrieve updates to the folder, following the same rules as documented for list_folder.
261
     *
262
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder-continue
263
     */
264
    public function listFolderContinue(string $cursor = ''): array
265
    {
266
        return $this->rpcEndpointRequest('files/list_folder/continue', compact('cursor'));
267
    }
268
269
    /**
270
     * Move a file or folder to a different location in the user's Dropbox.
271
     *
272
     * If the source path is a folder all its contents will be moved.
273
     *
274
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-move_v2
275
     */
276 View Code Duplication
    public function move(string $fromPath, string $toPath): array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
277
    {
278
        $parameters = [
279
            'from_path' => $this->normalizePath($fromPath),
280
            'to_path' => $this->normalizePath($toPath),
281
        ];
282
283
        return $this->rpcEndpointRequest('files/move_v2', $parameters);
284
    }
285
286
    /**
287
     * The file should be uploaded in chunks if it size exceeds the 150 MB threshold
288
     * or if the resource size could not be determined (eg. a popen() stream).
289
     *
290
     * @param string|resource $contents
291
     *
292
     * @return bool
293
     */
294
    protected function shouldUploadChunked($contents): bool
295
    {
296
        $size = is_string($contents) ? strlen($contents) : fstat($contents)['size'];
297
298
        if ($this->isPipe($contents)) {
299
            return true;
300
        }
301
302
        if ($size === null) {
303
            return true;
304
        }
305
306
        return $size > $this->maxChunkSize;
307
    }
308
309
    /**
310
     * Check if the contents is a pipe stream (not seekable, no size defined).
311
     *
312
     * @param string|resource $contents
313
     *
314
     * @return bool
315
     */
316
    protected function isPipe($contents): bool
317
    {
318
        return is_resource($contents) ? (fstat($contents)['mode'] & 010000) != 0 : false;
319
    }
320
321
    /**
322
     * Create a new file with the contents provided in the request.
323
     *
324
     * Do not use this to upload a file larger than 150 MB. Instead, create an upload session with upload_session/start.
325
     *
326
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload
327
     *
328
     * @param string $path
329
     * @param string|resource $contents
330
     * @param string $mode
331
     *
332
     * @return array
333
     */
334
    public function upload(string $path, $contents, $mode = 'add'): array
335
    {
336
        if ($this->shouldUploadChunked($contents)) {
337
            return $this->uploadChunked($path, $contents, $mode);
338
        }
339
340
        $arguments = [
341
            'path' => $this->normalizePath($path),
342
            'mode' => $mode,
343
        ];
344
345
        $response = $this->contentEndpointRequest('files/upload', $arguments, $contents);
346
347
        $metadata = json_decode($response->getBody(), true);
348
349
        $metadata['.tag'] = 'file';
350
351
        return $metadata;
352
    }
353
354
    /**
355
     * Upload file split in chunks. This allows uploading large files, since
356
     * Dropbox API v2 limits the content size to 150MB.
357
     *
358
     * The chunk size will affect directly the memory usage, so be careful.
359
     * Large chunks tends to speed up the upload, while smaller optimizes memory usage.
360
     *
361
     * @param string          $path
362
     * @param string|resource $contents
363
     * @param string          $mode
364
     * @param int             $chunkSize
365
     *
366
     * @return array
367
     */
368
    public function uploadChunked(string $path, $contents, $mode = 'add', $chunkSize = null): array
369
    {
370
        if ($chunkSize === null || $chunkSize > $this->maxChunkSize) {
371
            $chunkSize = $this->maxChunkSize;
372
        }
373
374
        if ($this->isPipe($contents)) {
375
            /** @var resource $contents */
376
            $stream = new \GuzzleHttp\Psr7\PumpStream(function($length) use($contents) {
377
                $data = fread($contents, $length);
378
                if(strlen($data) === 0)
379
                    return false;
380
                return $data;
381
            });
382
        } else {
383
            $stream = Psr7\stream_for($contents);
384
        }
385
386
387
        $cursor = $this->uploadChunk(self::UPLOAD_SESSION_START, $stream, $chunkSize, null);
0 ignored issues
show
Bug introduced by
It seems like $stream defined by new \GuzzleHttp\Psr7\Pum... } return $data; }) on line 376 can also be of type object<GuzzleHttp\Psr7\PumpStream>; however, Spatie\Dropbox\Client::uploadChunk() does only seem to accept object<GuzzleHttp\Psr7\Stream>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
388
389
        while (! $stream->eof()) {
390
            $cursor = $this->uploadChunk(self::UPLOAD_SESSION_APPEND, $stream, $chunkSize, $cursor);
391
        }
392
393
        return $this->uploadSessionFinish('', $cursor, $path, $mode);
394
    }
395
396
    /**
397
     * @param int         $type
398
     * @param Psr7\Stream $stream
399
     * @param int         $chunkSize
400
     * @param \Spatie\Dropbox\UploadSessionCursor|null $cursor
401
     * @return \Spatie\Dropbox\UploadSessionCursor
402
     * @throws Exception
403
     */
404
    protected function uploadChunk($type, &$stream, $chunkSize, $cursor = null): UploadSessionCursor
405
    {
406
        $maximumTries = $stream->isSeekable() ? $this->maxUploadChunkRetries : 0;
407
        $pos = $stream->tell();
408
409
        $tries = 0;
410
411
        tryUpload:
412
        try {
413
            $tries++;
414
415
            $chunkStream = new Psr7\LimitStream($stream, $chunkSize, $stream->tell());
416
417
            if ($type === self::UPLOAD_SESSION_START) {
418
                return $this->uploadSessionStart($chunkStream);
419
            }
420
421
            if ($type === self::UPLOAD_SESSION_APPEND && $cursor !== null) {
422
                return $this->uploadSessionAppend($chunkStream, $cursor);
423
            }
424
425
            throw new Exception('Invalid type');
426
        } catch (RequestException $exception) {
427
            if ($tries < $maximumTries) {
428
                // rewind
429
                $stream->seek($pos, SEEK_SET);
430
                goto tryUpload;
431
            }
432
            throw $exception;
433
        }
434
    }
435
436
    /**
437
     * Upload sessions allow you to upload a single file in one or more requests,
438
     * for example where the size of the file is greater than 150 MB.
439
     * This call starts a new upload session with the given data.
440
     *
441
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-start
442
     *
443
     * @param string|StreamInterface $contents
444
     * @param bool   $close
445
     *
446
     * @return UploadSessionCursor
447
     */
448
    public function uploadSessionStart($contents, bool $close = false): UploadSessionCursor
449
    {
450
        $arguments = compact('close');
451
452
        $response = json_decode(
453
            $this->contentEndpointRequest('files/upload_session/start', $arguments, $contents)->getBody(),
454
            true
455
        );
456
457
        return new UploadSessionCursor($response['session_id'], ($contents instanceof StreamInterface ? $contents->tell() : strlen($contents)));
458
    }
459
460
    /**
461
     * Append more data to an upload session.
462
     * When the parameter close is set, this call will close the session.
463
     * A single request should not upload more than 150 MB.
464
     *
465
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-append_v2
466
     *
467
     * @param string|StreamInterface $contents
468
     * @param UploadSessionCursor $cursor
469
     * @param bool                $close
470
     *
471
     * @return \Spatie\Dropbox\UploadSessionCursor
472
     */
473
    public function uploadSessionAppend($contents, UploadSessionCursor $cursor, bool $close = false): UploadSessionCursor
474
    {
475
        $arguments = compact('cursor', 'close');
476
477
        $pos = $contents instanceof StreamInterface ? $contents->tell() : 0;
478
        $this->contentEndpointRequest('files/upload_session/append_v2', $arguments, $contents);
479
480
        $cursor->offset += $contents instanceof StreamInterface ? ($contents->tell() - $pos) : strlen($contents);
481
482
        return $cursor;
483
    }
484
485
    /**
486
     * Finish an upload session and save the uploaded data to the given file path.
487
     * A single request should not upload more than 150 MB.
488
     *
489
     * @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-finish
490
     *
491
     * @param string|StreamInterface              $contents
492
     * @param \Spatie\Dropbox\UploadSessionCursor $cursor
493
     * @param string                              $path
494
     * @param string|array                        $mode
495
     * @param bool                                $autorename
496
     * @param bool                                $mute
497
     *
498
     * @return array
499
     */
500
    public function uploadSessionFinish($contents, UploadSessionCursor $cursor, string $path, $mode = 'add', $autorename = false, $mute = false): array
501
    {
502
        $arguments = compact('cursor');
503
        $arguments['commit'] = compact('path', 'mode', 'autorename', 'mute');
504
505
        $response = $this->contentEndpointRequest(
506
            'files/upload_session/finish',
507
            $arguments,
508
            ($contents == '') ? null : $contents
509
        );
510
511
        $metadata = json_decode($response->getBody(), true);
512
513
        $metadata['.tag'] = 'file';
514
515
        return $metadata;
516
    }
517
518
    /**
519
     * Get Account Info for current authenticated user.
520
     *
521
     * @link https://www.dropbox.com/developers/documentation/http/documentation#users-get_current_account
522
     *
523
     * @return array
524
     */
525
    public function getAccountInfo(): array
526
    {
527
        return $this->rpcEndpointRequest('users/get_current_account');
528
    }
529
530
    /**
531
     * Revoke current access token.
532
     *
533
     * @link https://www.dropbox.com/developers/documentation/http/documentation#auth-token-revoke
534
     */
535
    public function revokeToken()
536
    {
537
        $this->rpcEndpointRequest('auth/token/revoke');
538
    }
539
540
    protected function normalizePath(string $path): string
541
    {
542
        if (preg_match("/^id:.*|^rev:.*|^(ns:[0-9]+(\/.*)?)/", $path) === 1) {
543
            return $path;
544
        }
545
546
        $path = trim($path, '/');
547
548
        return ($path === '') ? '' : '/'.$path;
549
    }
550
551
    /**
552
     * @param string $endpoint
553
     * @param array $arguments
554
     * @param string|resource|StreamInterface $body
555
     *
556
     * @return \Psr\Http\Message\ResponseInterface
557
     *
558
     * @throws \Exception
559
     */
560
    public function contentEndpointRequest(string $endpoint, array $arguments, $body = ''): ResponseInterface
561
    {
562
        $headers = ['Dropbox-API-Arg' => json_encode($arguments)];
563
564
        if ($body !== '') {
565
            $headers['Content-Type'] = 'application/octet-stream';
566
        }
567
568
        try {
569
            $response = $this->client->post("https://content.dropboxapi.com/2/{$endpoint}", [
570
                'headers' => $headers,
571
                'body' => $body,
572
            ]);
573
        } catch (ClientException $exception) {
574
            throw $this->determineException($exception);
575
        }
576
577
        return $response;
578
    }
579
580
    public function rpcEndpointRequest(string $endpoint, array $parameters = null): array
581
    {
582
        try {
583
            $options = [];
584
585
            if ($parameters) {
586
                $options['json'] = $parameters;
587
            }
588
589
            $response = $this->client->post("https://api.dropboxapi.com/2/{$endpoint}", $options);
590
        } catch (ClientException $exception) {
591
            throw $this->determineException($exception);
592
        }
593
594
        $response = json_decode($response->getBody(), true);
595
596
        return $response ?? [];
597
    }
598
599
    protected function determineException(ClientException $exception): Exception
600
    {
601
        if (in_array($exception->getResponse()->getStatusCode(), [400, 409])) {
602
            return new BadRequest($exception->getResponse());
0 ignored issues
show
Bug introduced by
It seems like $exception->getResponse() can be null; however, __construct() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
603
        }
604
605
        return $exception;
606
    }
607
}
608