-
Notifications
You must be signed in to change notification settings - Fork 179
/
Copy pathDropbox.php
1291 lines (1120 loc) · 41 KB
/
Dropbox.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Kunnu\Dropbox;
use Kunnu\Dropbox\Models\DeletedMetadata;
use Kunnu\Dropbox\Models\File;
use Kunnu\Dropbox\Models\Account;
use Kunnu\Dropbox\Models\Thumbnail;
use Kunnu\Dropbox\Models\AccountList;
use Kunnu\Dropbox\Models\ModelFactory;
use Kunnu\Dropbox\Models\FileMetadata;
use Kunnu\Dropbox\Models\CopyReference;
use Kunnu\Dropbox\Models\FolderMetadata;
use Kunnu\Dropbox\Models\ModelCollection;
use Kunnu\Dropbox\Authentication\OAuth2Client;
use Kunnu\Dropbox\Store\PersistentDataStoreFactory;
use Kunnu\Dropbox\Authentication\DropboxAuthHelper;
use Kunnu\Dropbox\Exceptions\DropboxClientException;
use Kunnu\Dropbox\Security\RandomStringGeneratorFactory;
use Kunnu\Dropbox\Http\Clients\DropboxHttpClientFactory;
/**
* Dropbox
*/
class Dropbox
{
/**
* Uploading a file with the 'uploadFile' method, with the file's
* size less than this value (~8 MB), the simple `upload` method will be
* used, if the file size exceed this value (~8 MB), the `startUploadSession`,
* `appendUploadSession` & `finishUploadSession` methods will be used
* to upload the file in chunks.
*
* @const int
*/
const AUTO_CHUNKED_UPLOAD_THRESHOLD = 8000000;
/**
* The Chunk Size the file will be
* split into and uploaded (~4 MB)
*
* @const int
*/
const DEFAULT_CHUNK_SIZE = 4000000;
/**
* Response header containing file metadata
*
* @const string
*/
const METADATA_HEADER = 'Dropbox-Api-Result';
/**
* The Dropbox App
*
* @var \Kunnu\Dropbox\DropboxApp
*/
protected $app;
/**
* OAuth2 Access Token
*
* @var string
*/
protected $accessToken;
/**
* Dropbox Client
*
* @var \Kunnu\Dropbox\DropboxClient
*/
protected $client;
/**
* OAuth2 Client
*
* @var \Kunnu\Dropbox\Authentication\OAuth2Client
*/
protected $oAuth2Client;
/**
* Random String Generator
*
* @var \Kunnu\Dropbox\Security\RandomStringGeneratorInterface
*/
protected $randomStringGenerator;
/**
* Persistent Data Store
*
* @var \Kunnu\Dropbox\Store\PersistentDataStoreInterface
*/
protected $persistentDataStore;
/**
* Create a new Dropbox instance
*
* @param \Kunnu\Dropbox\DropboxApp
* @param array $config Configuration Array
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*/
public function __construct(DropboxApp $app, array $config = [])
{
//Configuration
$config = array_merge([
'http_client_handler' => null,
'random_string_generator' => null,
'persistent_data_store' => null
], $config);
//Set the app
$this->app = $app;
//Set the access token
$this->setAccessToken($app->getAccessToken());
//Make the HTTP Client
$httpClient = DropboxHttpClientFactory::make($config['http_client_handler']);
//Make and Set the DropboxClient
$this->client = new DropboxClient($httpClient);
//Make and Set the Random String Generator
$this->randomStringGenerator = RandomStringGeneratorFactory::makeRandomStringGenerator($config['random_string_generator']);
//Make and Set the Persistent Data Store
$this->persistentDataStore = PersistentDataStoreFactory::makePersistentDataStore($config['persistent_data_store']);
}
/**
* Get Dropbox Auth Helper
*
* @return \Kunnu\Dropbox\Authentication\DropboxAuthHelper
*/
public function getAuthHelper()
{
return new DropboxAuthHelper(
$this->getOAuth2Client(),
$this->getRandomStringGenerator(),
$this->getPersistentDataStore()
);
}
/**
* Get OAuth2Client
*
* @return \Kunnu\Dropbox\Authentication\OAuth2Client
*/
public function getOAuth2Client()
{
if (!$this->oAuth2Client instanceof OAuth2Client) {
return new OAuth2Client(
$this->getApp(),
$this->getClient(),
$this->getRandomStringGenerator()
);
}
return $this->oAuth2Client;
}
/**
* Get the Dropbox App.
*
* @return \Kunnu\Dropbox\DropboxApp Dropbox App
*/
public function getApp()
{
return $this->app;
}
/**
* Get the Client
*
* @return \Kunnu\Dropbox\DropboxClient
*/
public function getClient()
{
return $this->client;
}
/**
* Get the Random String Generator
*
* @return \Kunnu\Dropbox\Security\RandomStringGeneratorInterface
*/
public function getRandomStringGenerator()
{
return $this->randomStringGenerator;
}
/**
* Get Persistent Data Store
*
* @return \Kunnu\Dropbox\Store\PersistentDataStoreInterface
*/
public function getPersistentDataStore()
{
return $this->persistentDataStore;
}
/**
* Get the Metadata for a file or folder
*
* @param string $path Path of the file or folder
* @param array $params Additional Params
*
* @return \Kunnu\Dropbox\Models\FileMetadata | \Kunnu\Dropbox\Models\FolderMetadata
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-get_metadata
*
*/
public function getMetadata($path, array $params = [])
{
//Root folder is unsupported
if ($path === '/') {
throw new DropboxClientException("Metadata for the root folder is unsupported.");
}
//Set the path
$params['path'] = $path;
//Get File Metadata
$response = $this->postToAPI('/files/get_metadata', $params);
//Make and Return the Model
return $this->makeModelFromResponse($response);
}
/**
* Make a HTTP POST Request to the API endpoint type
*
* @param string $endpoint API Endpoint to send Request to
* @param array $params Request Query Params
* @param string $accessToken Access Token to send with the Request
*
* @return \Kunnu\Dropbox\DropboxResponse
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*/
public function postToAPI($endpoint, array $params = [], $accessToken = null)
{
return $this->sendRequest("POST", $endpoint, 'api', $params, $accessToken);
}
/**
* Make Request to the API
*
* @param string $method HTTP Request Method
* @param string $endpoint API Endpoint to send Request to
* @param string $endpointType Endpoint type ['api'|'content']
* @param array $params Request Query Params
* @param string $accessToken Access Token to send with the Request
* @param DropboxFile $responseFile Save response to the file
*
* @return \Kunnu\Dropbox\DropboxResponse
*
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*/
public function sendRequest($method, $endpoint, $endpointType = 'api', array $params = [], $accessToken = null, DropboxFile $responseFile = null)
{
//Access Token
$accessToken = $this->getAccessToken() ? $this->getAccessToken() : $accessToken;
//Make a DropboxRequest object
$request = new DropboxRequest($method, $endpoint, $accessToken, $endpointType, $params);
//Make a DropboxResponse object if a response should be saved to the file
$response = $responseFile ? new DropboxResponseToFile($request, $responseFile) : null;
//Send Request through the DropboxClient
//Fetch and return the Response
return $this->getClient()->sendRequest($request, $response);
}
/**
* Get the Access Token.
*
* @return string Access Token
*/
public function getAccessToken()
{
return $this->accessToken;
}
/**
* Set the Access Token.
*
* @param string $accessToken Access Token
*
* @return \Kunnu\Dropbox\Dropbox Dropbox Client
*/
public function setAccessToken($accessToken)
{
$this->accessToken = $accessToken;
return $this;
}
/**
* Make Model from DropboxResponse
*
* @param DropboxResponse $response
*
* @return \Kunnu\Dropbox\Models\ModelInterface
*
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*/
public function makeModelFromResponse(DropboxResponse $response)
{
//Get the Decoded Body
$body = $response->getDecodedBody();
if (is_null($body)) {
$body = [];
}
//Make and Return the Model
return ModelFactory::make($body);
}
/**
* Get the contents of a Folder
*
* @param string $path Path to the folder. Defaults to root.
* @param array $params Additional Params
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder
*
* @return \Kunnu\Dropbox\Models\MetadataCollection
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*/
public function listFolder($path = null, array $params = [])
{
//Specify the root folder as an
//empty string rather than as "/"
if ($path === '/') {
$path = "";
}
//Set the path
$params['path'] = $path;
//Get File Metadata
$response = $this->postToAPI('/files/list_folder', $params);
//Make and Return the Model
return $this->makeModelFromResponse($response);
}
/**
* Paginate through all files and retrieve updates to the folder,
* using the cursor retrieved from listFolder or listFolderContinue
*
* @param string $cursor The cursor returned by your
* last call to listFolder or listFolderContinue
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder-continue
*
* @return \Kunnu\Dropbox\Models\MetadataCollection
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*/
public function listFolderContinue($cursor)
{
$response = $this->postToAPI('/files/list_folder/continue', ['cursor' => $cursor]);
//Make and Return the Model
return $this->makeModelFromResponse($response);
}
/**
* Get a cursor for the folder's state.
*
* @param string $path Path to the folder. Defaults to root.
* @param array $params Additional Params
*
* @return string The Cursor for the folder's state
*
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_folder-get_latest_cursor
*
*/
public function listFolderLatestCursor($path, array $params = [])
{
//Specify the root folder as an
//empty string rather than as "/"
if ($path === '/') {
$path = "";
}
//Set the path
$params['path'] = $path;
//Fetch the cursor
$response = $this->postToAPI('/files/list_folder/get_latest_cursor', $params);
//Retrieve the cursor
$body = $response->getDecodedBody();
$cursor = isset($body['cursor']) ? $body['cursor'] : false;
//No cursor returned
if (!$cursor) {
throw new DropboxClientException("Could not retrieve cursor. Something went wrong.");
}
//Return the cursor
return $cursor;
}
/**
* Get Revisions of a File
*
* @param string $path Path to the file
* @param array $params Additional Params
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-list_revisions
*
* @return \Kunnu\Dropbox\Models\ModelCollection
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*/
public function listRevisions($path, array $params = [])
{
//Set the Path
$params['path'] = $path;
//Fetch the Revisions
$response = $this->postToAPI('/files/list_revisions', $params);
//The file metadata of the entries, returned by this
//endpoint doesn't include a '.tag' attribute, which
//is used by the ModelFactory to resolve the correct
//model. But since we know that revisions returned
//are file metadata objects, we can explicitly cast
//them as \Kunnu\Dropbox\Models\FileMetadata manually.
$body = $response->getDecodedBody();
$entries = isset($body['entries']) ? $body['entries'] : [];
$processedEntries = [];
foreach ($entries as $entry) {
$processedEntries[] = new FileMetadata($entry);
}
return new ModelCollection($processedEntries);
}
/**
* Search a folder for files/folders
*
* @param string $path Path to search
* @param string $query Search Query
* @param array $params Additional Params
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-search
*
* @return \Kunnu\Dropbox\Models\SearchResults
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*/
public function search($path, $query, array $params = [])
{
//Specify the root folder as an
//empty string rather than as "/"
if ($path === '/') {
$path = "";
}
//Set the path and query
$params['path'] = $path;
$params['query'] = $query;
//Fetch Search Results
$response = $this->postToAPI('/files/search', $params);
//Make and Return the Model
return $this->makeModelFromResponse($response);
}
/**
* Create a folder at the given path
*
* @param string $path Path to create
* @param boolean $autorename Auto Rename File
*
* @return \Kunnu\Dropbox\Models\FolderMetadata
*
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-create_folder
*
*/
public function createFolder($path, $autorename = false)
{
//Path cannot be null
if (is_null($path)) {
throw new DropboxClientException("Path cannot be null.");
}
//Create Folder
$response = $this->postToAPI('/files/create_folder', ['path' => $path, 'autorename' => $autorename]);
//Fetch the Metadata
$body = $response->getDecodedBody();
//Make and Return the Model
return new FolderMetadata($body);
}
/**
* Delete a file or folder at the given path
*
* @param string $path Path to file/folder to delete
*
* @return \Kunnu\Dropbox\Models\DeletedMetadata
*
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-delete
*
*/
public function delete($path)
{
//Path cannot be null
if (is_null($path)) {
throw new DropboxClientException("Path cannot be null.");
}
//Delete
$response = $this->postToAPI('/files/delete_v2', ['path' => $path]);
$body = $response->getDecodedBody();
//Response doesn't have Metadata
if (!isset($body['metadata']) || !is_array($body['metadata'])) {
throw new DropboxClientException("Invalid Response.");
}
return new DeletedMetadata($body['metadata']);
}
/**
* Move a file or folder to a different location
*
* @param string $fromPath Path to be moved
* @param string $toPath Path to be moved to
*
* @return \Kunnu\Dropbox\Models\DeletedMetadata|\Kunnu\Dropbox\Models\FileMetadata
*
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-move
*
*/
public function move($fromPath, $toPath)
{
//From and To paths cannot be null
if (is_null($fromPath) || is_null($toPath)) {
throw new DropboxClientException("From and To paths cannot be null.");
}
//Response
$response = $this->postToAPI('/files/move', ['from_path' => $fromPath, 'to_path' => $toPath]);
//Make and Return the Model
return $this->makeModelFromResponse($response);
}
/**
* Copy a file or folder to a different location
*
* @param string $fromPath Path to be copied
* @param string $toPath Path to be copied to
*
* @return \Kunnu\Dropbox\Models\DeletedMetadata|\Kunnu\Dropbox\Models\FileMetadata
*
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy
*
*/
public function copy($fromPath, $toPath)
{
//From and To paths cannot be null
if (is_null($fromPath) || is_null($toPath)) {
throw new DropboxClientException("From and To paths cannot be null.");
}
//Response
$response = $this->postToAPI('/files/copy', ['from_path' => $fromPath, 'to_path' => $toPath]);
//Make and Return the Model
return $this->makeModelFromResponse($response);
}
/**
* Restore a file to the specific version
*
* @param string $path Path to the file to restore
* @param string $rev Revision to store for the file
*
* @return \Kunnu\Dropbox\Models\DeletedMetadata|\Kunnu\Dropbox\Models\FileMetadata|\Kunnu\Dropbox\Models\FolderMetadata
*
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-restore
*
*/
public function restore($path, $rev)
{
//Path and Revision cannot be null
if (is_null($path) || is_null($rev)) {
throw new DropboxClientException("Path and Revision cannot be null.");
}
//Response
$response = $this->postToAPI('/files/restore', ['path' => $path, 'rev' => $rev]);
//Fetch the Metadata
$body = $response->getDecodedBody();
//Make and Return the Model
return new FileMetadata($body);
}
/**
* Get Copy Reference
*
* @param string $path Path to the file or folder to get a copy reference to
*
* @return \Kunnu\Dropbox\Models\CopyReference
*
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy_reference-get
*
*/
public function getCopyReference($path)
{
//Path cannot be null
if (is_null($path)) {
throw new DropboxClientException("Path cannot be null.");
}
//Get Copy Reference
$response = $this->postToAPI('/files/copy_reference/get', ['path' => $path]);
$body = $response->getDecodedBody();
//Make and Return the Model
return new CopyReference($body);
}
/**
* Save Copy Reference
*
* @param string $path Path to the file or folder to get a copy reference to
* @param string $copyReference Copy reference returned by getCopyReference
*
* @return \Kunnu\Dropbox\Models\FileMetadata|\Kunnu\Dropbox\Models\FolderMetadata
*
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-copy_reference-save
*
*/
public function saveCopyReference($path, $copyReference)
{
//Path and Copy Reference cannot be null
if (is_null($path) || is_null($copyReference)) {
throw new DropboxClientException("Path and Copy Reference cannot be null.");
}
//Save Copy Reference
$response = $this->postToAPI('/files/copy_reference/save', ['path' => $path, 'copy_reference' => $copyReference]);
$body = $response->getDecodedBody();
//Response doesn't have Metadata
if (!isset($body['metadata']) || !is_array($body['metadata'])) {
throw new DropboxClientException("Invalid Response.");
}
//Make and return the Model
return ModelFactory::make($body['metadata']);
}
/**
* Get a temporary link to stream contents of a file
*
* @param string $path Path to the file you want a temporary link to
*
* https://www.dropbox.com/developers/documentation/http/documentation#files-get_temporary_link
*
* @return \Kunnu\Dropbox\Models\TemporaryLink
*
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*/
public function getTemporaryLink($path)
{
//Path cannot be null
if (is_null($path)) {
throw new DropboxClientException("Path cannot be null.");
}
//Get Temporary Link
$response = $this->postToAPI('/files/get_temporary_link', ['path' => $path]);
//Make and Return the Model
return $this->makeModelFromResponse($response);
}
/**
* Save a specified URL into a file in user's Dropbox
*
* @param string $path Path where the URL will be saved
* @param string $url URL to be saved
*
* @return string Async Job ID
*
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-save_url
*
*/
public function saveUrl($path, $url)
{
//Path and URL cannot be null
if (is_null($path) || is_null($url)) {
throw new DropboxClientException("Path and URL cannot be null.");
}
//Save URL
$response = $this->postToAPI('/files/save_url', ['path' => $path, 'url' => $url]);
$body = $response->getDecodedBody();
if (!isset($body['async_job_id'])) {
throw new DropboxClientException("Could not retrieve Async Job ID.");
}
//Return the Async Job ID
return $body['async_job_id'];
}
/**
* Save a specified URL into a file in user's Dropbox
*
* @param $asyncJobId
*
* @return \Kunnu\Dropbox\Models\FileMetadata|string Status (failed|in_progress) or FileMetadata (if complete)
*
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-save_url-check_job_status
*
*/
public function checkJobStatus($asyncJobId)
{
//Async Job ID cannot be null
if (is_null($asyncJobId)) {
throw new DropboxClientException("Async Job ID cannot be null.");
}
//Get Job Status
$response = $this->postToAPI('/files/save_url/check_job_status', ['async_job_id' => $asyncJobId]);
$body = $response->getDecodedBody();
//Status
$status = isset($body['.tag']) ? $body['.tag'] : '';
//If status is complete
if ($status === 'complete') {
return new FileMetadata($body);
}
//Return the status
return $status;
}
/**
* Upload a File to Dropbox
*
* @param string|DropboxFile $dropboxFile DropboxFile object or Path to file
* @param string $path Path to upload the file to
* @param array $params Additional Params
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload
*
* @return \Kunnu\Dropbox\Models\FileMetadata
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*/
public function upload($dropboxFile, $path, array $params = [])
{
//Make Dropbox File
$dropboxFile = $this->makeDropboxFile($dropboxFile);
//If the file is larger than the Chunked Upload Threshold
if ($dropboxFile->getSize() > static::AUTO_CHUNKED_UPLOAD_THRESHOLD) {
//Upload the file in sessions/chunks
return $this->uploadChunked($dropboxFile, $path, null, null, $params);
}
//Simple file upload
return $this->simpleUpload($dropboxFile, $path, $params);
}
/**
* Make DropboxFile Object
*
* @param string|DropboxFile $dropboxFile DropboxFile object or Path to file
* @param int $maxLength Max Bytes to read from the file
* @param int $offset Seek to specified offset before reading
* @param string $mode The type of access
*
* @return \Kunnu\Dropbox\DropboxFile
*/
public function makeDropboxFile($dropboxFile, $maxLength = null, $offset = null, $mode = DropboxFile::MODE_READ)
{
//Uploading file by file path
if (!$dropboxFile instanceof DropboxFile) {
//Create a DropboxFile Object
$dropboxFile = new DropboxFile($dropboxFile, $mode);
} elseif ($mode !== $dropboxFile->getMode()) {
//Reopen the file with expected mode
$dropboxFile->close();
$dropboxFile = new DropboxFile($dropboxFile->getFilePath(), $mode);
}
if (!is_null($offset)) {
$dropboxFile->setOffset($offset);
}
if (!is_null($maxLength)) {
$dropboxFile->setMaxLength($maxLength);
}
//Return the DropboxFile Object
return $dropboxFile;
}
/**
* Upload file in sessions/chunks
*
* @param string|DropboxFile $dropboxFile DropboxFile object or Path to file
* @param string $path Path to save the file to, on Dropbox
* @param int $fileSize The size of the file
* @param int $chunkSize The amount of data to upload in each chunk
* @param array $params Additional Params
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-start
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-finish
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-append_v2
*
* @return \Kunnu\Dropbox\Models\FileMetadata
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*/
public function uploadChunked($dropboxFile, $path, $fileSize = null, $chunkSize = null, array $params = array())
{
//Make Dropbox File
$dropboxFile = $this->makeDropboxFile($dropboxFile);
//No file size specified explicitly
if (is_null($fileSize)) {
$fileSize = $dropboxFile->getSize();
}
//No chunk size specified, use default size
if (is_null($chunkSize)) {
$chunkSize = static::DEFAULT_CHUNK_SIZE;
}
//If the fileSize is smaller
//than the chunk size, we'll
//make the chunk size relatively
//smaller than the file size
if ($fileSize <= $chunkSize) {
$chunkSize = intval($fileSize / 2);
}
//Start the Upload Session with the file path
//since the DropboxFile object will be created
//again using the new chunk size.
$sessionId = $this->startUploadSession($dropboxFile->getFilePath(), $chunkSize);
//Uploaded
$uploaded = $chunkSize;
//Remaining
$remaining = $fileSize - $chunkSize;
//While the remaining bytes are
//more than the chunk size, append
//the chunk to the upload session.
while ($remaining > $chunkSize) {
//Append the next chunk to the Upload session
$sessionId = $this->appendUploadSession($dropboxFile, $sessionId, $uploaded, $chunkSize);
//Update remaining and uploaded
$uploaded = $uploaded + $chunkSize;
$remaining = $remaining - $chunkSize;
}
//Finish the Upload Session and return the Uploaded File Metadata
return $this->finishUploadSession($dropboxFile, $sessionId, $uploaded, $remaining, $path, $params);
}
/**
* Start an Upload Session
*
* @param string|DropboxFile $dropboxFile DropboxFile object or Path to file
* @param int $chunkSize Size of file chunk to upload
* @param boolean $close Closes the session for "appendUploadSession"
*
* @return string Unique identifier for the upload session
*
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-start
*
*/
public function startUploadSession($dropboxFile, $chunkSize = -1, $close = false)
{
//Make Dropbox File with the given chunk size
$dropboxFile = $this->makeDropboxFile($dropboxFile, $chunkSize);
//Set the close param
$params = [
'close' => $close ? true : false,
'file' => $dropboxFile
];
//Upload File
$file = $this->postToContent('/files/upload_session/start', $params);
$body = $file->getDecodedBody();
//Cannot retrieve Session ID
if (!isset($body['session_id'])) {
throw new DropboxClientException("Could not retrieve Session ID.");
}
//Return the Session ID
return $body['session_id'];
}
/**
* Make a HTTP POST Request to the Content endpoint type
*
* @param string $endpoint Content Endpoint to send Request to
* @param array $params Request Query Params
* @param string $accessToken Access Token to send with the Request
* @param DropboxFile $responseFile Save response to the file
*
* @return \Kunnu\Dropbox\DropboxResponse
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*/
public function postToContent($endpoint, array $params = [], $accessToken = null, DropboxFile $responseFile = null)
{
return $this->sendRequest("POST", $endpoint, 'content', $params, $accessToken, $responseFile);
}
/**
* Append more data to an Upload Session
*
* @param string|DropboxFile $dropboxFile DropboxFile object or Path to file
* @param string $sessionId Session ID returned by `startUploadSession`
* @param int $offset The amount of data that has been uploaded so far
* @param int $chunkSize The amount of data to upload
* @param boolean $close Closes the session for futher "appendUploadSession" calls
*
* @return string Unique identifier for the upload session
*
* @throws \Kunnu\Dropbox\Exceptions\DropboxClientException
*
* @link https://www.dropbox.com/developers/documentation/http/documentation#files-upload_session-append_v2
*
*/
public function appendUploadSession($dropboxFile, $sessionId, $offset, $chunkSize, $close = false)
{
//Make Dropbox File
$dropboxFile = $this->makeDropboxFile($dropboxFile, $chunkSize, $offset);
//Session ID, offset, chunkSize and path cannot be null
if (is_null($sessionId) || is_null($offset) || is_null($chunkSize)) {
throw new DropboxClientException("Session ID, offset and chunk size cannot be null");
}
$params = [];
//Set the File
$params['file'] = $dropboxFile;
//Set the Cursor: Session ID and Offset
$params['cursor'] = ['session_id' => $sessionId, 'offset' => $offset];
//Set the close param
$params['close'] = $close ? true : false;
//Since this endpoint doesn't have
//any return values, we'll disable the
//response validation for this request.
$params['validateResponse'] = false;
//Upload File
$this->postToContent('/files/upload_session/append_v2', $params);