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
Push — master ( cd0675...c31270 )
by Freek
12s
created

Client::uploadChunked()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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