forked from andreafabrizi/Dropbox-Uploader
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdropbox_uploader.sh
More file actions
executable file
·1983 lines (1596 loc) · 52.1 KB
/
dropbox_uploader.sh
File metadata and controls
executable file
·1983 lines (1596 loc) · 52.1 KB
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
#!/usr/bin/env bash
#
# Dropbox Uploader
#
# Copyright (C) 2010-2021 Andrea Fabrizi <andrea.fabrizi@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#Print the message based on $QUIET variable
print() {
if [[ $QUIET -eq 0 ]]; then
echo -ne "$1"
fi
}
#Returns unix timestamp
utime() {
date '+%s'
}
#Remove temporary files
remove_temp_files() {
if [[ $DEBUG == 0 ]]; then
rm -fr "$RESPONSE_FILE"
rm -fr "$CHUNK_FILE"
rm -fr "$TEMP_FILE"
fi
}
#Converts bytes to human readable format
convert_bytes() {
if [[ $HUMAN_READABLE_SIZE == 1 && "$1" != "" ]]; then
if (($1 > 1073741824)); then
echo $(($1 / 1073741824)).$(($1 % 1073741824 / 100000000))"G"
elif (($1 > 1048576)); then
echo $(($1 / 1048576)).$(($1 % 1048576 / 100000))"M"
elif (($1 > 1024)); then
echo $(($1 / 1024)).$(($1 % 1024 / 100))"K"
else
echo "$1"
fi
else
echo "$1"
fi
}
#Returns the file size in bytes
file_size() {
local size
#Generic GNU
size=$(stat --format="%s" "$1" 2>/dev/null)
if [ $? -eq 0 ]; then
echo "$size"
return 0
fi
#Some embedded linux devices
size=$(stat -c "%s" "$1" 2>/dev/null)
if [ $? -eq 0 ]; then
echo "$size"
return 0
fi
#BSD, OSX and other OSs
size=$(stat -f "%z" "$1" 2>/dev/null)
if [ $? -eq 0 ]; then
echo "$size"
return 0
fi
echo "0"
}
#Usage
usage() {
echo -e "Dropbox Uploader v$VERSION"
echo -e "Andrea Fabrizi - andrea.fabrizi@gmail.com\n"
echo -e "Usage: $0 [PARAMETERS] COMMAND..."
echo -e "\nCommands:"
echo -e "\t upload <LOCAL_FILE/DIR ...> <REMOTE_FILE/DIR>"
echo -e "\t download <REMOTE_FILE/DIR> [LOCAL_FILE/DIR]"
echo -e "\t delete <REMOTE_FILE/DIR>"
echo -e "\t move <REMOTE_FILE/DIR> <REMOTE_FILE/DIR>"
echo -e "\t copy <REMOTE_FILE/DIR> <REMOTE_FILE/DIR>"
echo -e "\t mkdir <REMOTE_DIR>"
echo -e "\t list [REMOTE_DIR]"
echo -e "\t monitor [REMOTE_DIR] [TIMEOUT]"
echo -e "\t share <REMOTE_FILE>"
echo -e "\t saveurl <URL> <REMOTE_DIR>"
echo -e "\t search <QUERY>"
echo -e "\t info"
echo -e "\t space"
echo -e "\t unlink"
echo -e "\t reauth, reconfigure"
echo -e "\t test"
echo -e "\t version"
echo -e "\t show-script-path, get-script-path, script-path"
echo -e "\nOptional parameters:"
echo -e "\t-c <SIZE> Use chunk size (default: ${CHUNK_SIZE})"
echo -e "\t-f <FILENAME> Load the configuration file from a specific file"
echo -e "\t-s Skip already existing files when download/upload. Default: Overwrite"
echo -e "\t-d Enable DEBUG mode"
echo -e "\t-q Quiet mode. Don't show messages"
echo -e "\t-h Show file sizes in human readable format"
echo -e "\t-p Show cURL progress meter"
echo -e "\t-k Doesn't check for SSL certificates (insecure)"
echo -e "\t-x Ignores/excludes directories or files from syncing. -x filename -x directoryname. example: -x .git"
echo -en "\nFor more info and examples, please see the README file.\n\n"
remove_temp_files
exit 1
}
#Check the curl exit code
check_http_response() {
local code
code=$1
#Checking curl exit code
case $code in
#OK
0) ;;
#Proxy error
5)
print "\nError: Couldn't resolve proxy. The given proxy host could not be resolved.\n"
remove_temp_files
exit 1
;;
#Missing CA certificates
60 | 58 | 77)
print "\nError: cURL is not able to performs peer SSL certificate verification.\n"
print "Please, install the default ca-certificates bundle.\n"
print "To do this in a Debian/Ubuntu based system, try:\n"
print " sudo apt-get install ca-certificates\n\n"
print "If the problem persists, try to use the -k option (insecure).\n"
remove_temp_files
exit 1
;;
6)
print "\nError: Couldn't resolve host.\n"
remove_temp_files
exit 1
;;
7)
print "\nError: Couldn't connect to host.\n"
remove_temp_files
exit 1
;;
esac
#Checking response file for generic errors
if grep -q "^HTTP/[12].* 400" "$RESPONSE_FILE"; then
local error_msg
error_msg=$(sed -n -e 's/{"error": "\([^"]*\)"}/\1/p' "$RESPONSE_FILE")
case $error_msg in
*access?attempt?failed?because?this?app?is?not?configured?to?have*)
echo -e "\nError: The Permission type/Access level configured doesn't match the DropBox App settings!\nPlease run \"$0 unlink\" and try again."
exit 1
;;
esac
fi
}
# Checks if the access token has expired. If so a new one is created.
ensure_accesstoken() {
local now expires_in
now=$(date +%s)
# This does not do anything
if [[ $OAUTH_ACCESS_TOKEN_EXPIRE > $now ]]; then
return 1
fi
$CURL_BIN $CURL_ACCEPT_CERTIFICATES $API_OAUTH_TOKEN -d grant_type=refresh_token -d refresh_token=$OAUTH_REFRESH_TOKEN -u $OAUTH_APP_KEY:$OAUTH_APP_SECRET -o "$RESPONSE_FILE" 2>/dev/null
check_http_response $?
OAUTH_ACCESS_TOKEN=$(sed -n 's/.*"access_token": "\([^"]*\).*/\1/p' "$RESPONSE_FILE")
expires_in=$(sed -n 's/.*"expires_in": \([0-9]*\).*/\1/p' "$RESPONSE_FILE")
# one minute safety buffer
OAUTH_ACCESS_TOKEN_EXPIRE=$((now + expires_in - 60))
}
#Urlencode
urlencode() {
local string strlen encoded
#The printf is necessary to correctly decode unicode sequences
string=$($PRINTF "%s" "${1}")
strlen=${#string}
encoded=""
for ((pos = 0; pos < strlen; pos++)); do
local c
c=${string:$pos:1}
case "$c" in
[-_.~a-zA-Z0-9]) o="${c}" ;;
*) $PRINTF $PRINTF_OPT '%%%02x' "'$c" ;;
esac
encoded="${encoded}${o}"
done
echo "$encoded"
}
normalize_path() {
local path new_path
#The printf is necessary to correctly decode unicode sequences
path=$($PRINTF "%s" "${1//\/\///}")
if [[ $HAVE_READLINK == 1 ]]; then
new_path=$(readlink -m "$path")
#Adding back the final slash, if present in the source
if [[ ${path: -1} == "/" && ${#path} -gt 1 ]]; then
new_path="$new_path/"
fi
echo "$new_path"
else
echo "$path"
fi
}
#Check if it's a file or directory
#Returns FILE/DIR/ERR
db_stat() {
local file type
file=$(normalize_path "$1")
if [[ $file == "/" ]]; then
echo "DIR"
return 0
fi
#Checking if it's a file or a directory
ensure_accesstoken
$CURL_BIN $CURL_ACCEPT_CERTIFICATES -X POST -L -s --show-error --globoff -i -o "$RESPONSE_FILE" --header "Authorization: Bearer $OAUTH_ACCESS_TOKEN" --header "Content-Type: application/json" --data "{\"path\": \"$file\"}" "$API_METADATA_URL" 2>/dev/null
check_http_response $?
type=$(sed -n 's/{".tag": *"*\([^"]*\)"*.*/\1/p' "$RESPONSE_FILE")
case $type in
file)
echo "FILE"
;;
folder)
echo "DIR"
;;
deleted)
echo "ERR"
;;
*)
echo "ERR"
;;
esac
}
#Generic upload wrapper around db_upload_file and db_upload_dir functions
#$1 = Local source file/dir
#$2 = Remote destination file/dir
db_upload() {
local src dst type
src=$(normalize_path "$1")
dst=$(normalize_path "$2")
for j in "${EXCLUDE[@]}"; do
echo "$src" | grep -c "$j"
if [[ $(echo "$src" | grep -c "$j") -gt 0 ]]; then
print "Skipping excluded file/dir: $j"
return 1
fi
done
#Checking if the file/dir exists
if [[ ! -e $src && ! -d $src ]]; then
print " > No such file or directory: $src\n"
ERROR_STATUS=1
return 1
fi
#Checking if the file/dir has read permissions
if [[ ! -r $src ]]; then
print " > Error reading file $src: permission denied\n"
ERROR_STATUS=1
return 1
fi
type=$(db_stat "$dst")
#If dst it's a file, do nothing, it's the default behaviour
if [[ $type == "FILE" ]]; then
dst="$dst"
#if dst doesn't exists and doesn't ends with a /, it will be the destination file name
elif [[ $type == "ERR" && "${dst: -1}" != "/" ]]; then
dst="$dst"
#if dst doesn't exists and ends with a /, it will be the destination folder
elif [[ $type == "ERR" && "${dst: -1}" == "/" ]]; then
local filename
filename=$(basename "$src")
dst="$dst/$filename"
#If dst it's a directory, it will be the destination folder
elif [[ $type == "DIR" ]]; then
local filename
filename=$(basename "$src")
dst="$dst/$filename"
fi
#It's a directory
if [[ -d $src ]]; then
db_upload_dir "$src" "$dst"
#It's a file
elif [[ -e $src ]]; then
db_upload_file "$src" "$dst"
#Unsupported object...
else
print " > Skipping not regular file \"$src\"\n"
fi
}
#Generic upload wrapper around db_chunked_upload_file and db_simple_upload_file
#The final upload function will be choosen based on the file size
#$1 = Local source file
#$2 = Remote destination file
db_upload_file() {
local file_src file_dst file_size basefile_dst type
file_src=$(normalize_path "$1")
file_dst=$(normalize_path "$2")
shopt -s nocasematch
#Checking not allowed file names
basefile_dst=$(basename "$file_dst")
if [[ $basefile_dst == "thumbs.db" || $basefile_dst == "desktop.ini" || $basefile_dst == ".ds_store" || $basefile_dst == "icon\r" || $basefile_dst == ".dropbox" || $basefile_dst == ".dropbox.attr" ]] \
; then
print " > Skipping not allowed file name \"$file_dst\"\n"
return 1
fi
shopt -u nocasematch
#Checking file size
file_size=$(file_size "$file_src")
#Checking if the file already exists
type=$(db_stat "$file_dst")
if [[ $type != "ERR" && $SKIP_EXISTING_FILES == 1 ]]; then
print " > Skipping already existing file \"$file_dst\"\n"
return 1
fi
# Checking if the file has the correct check sum
if [[ $type != "ERR" ]]; then
local sha_src sha_dst
sha_src=$(db_sha_local "$file_src")
sha_dst=$(db_sha "$file_dst")
if [[ $sha_src == "$sha_dst" && $sha_src != "ERR" ]]; then
print "> Skipping file \"$file_src\", file exists with the same hash\n"
return 1
fi
fi
if [[ $file_size -gt 157286000 ]]; then
#If the file is greater than 150Mb, the chunked_upload API will be used
db_chunked_upload_file "$file_src" "$file_dst"
else
db_simple_upload_file "$file_src" "$file_dst"
fi
}
#Simple file upload
#$1 = Local source file
#$2 = Remote destination file
db_simple_upload_file() {
local file_src file_dst curl_parameters line_cr
file_src=$(normalize_path "$1")
file_dst=$(normalize_path "$2")
if [[ $SHOW_PROGRESSBAR == 1 && $QUIET == 0 ]]; then
curl_parameters="--progress-bar"
line_cr="\n"
else
curl_parameters="-L -s"
line_cr=""
fi
print " > Uploading \"$file_src\" to \"$file_dst\"... $line_cr"
ensure_accesstoken
$CURL_BIN $CURL_ACCEPT_CERTIFICATES $curl_parameters -X POST -i --globoff -o "$RESPONSE_FILE" --header "Authorization: Bearer $OAUTH_ACCESS_TOKEN" --header "Dropbox-API-Arg: {\"path\": \"$file_dst\",\"mode\": \"overwrite\",\"autorename\": true,\"mute\": false}" --header "Content-Type: application/octet-stream" --data-binary @"$file_src" "$API_UPLOAD_URL"
check_http_response $?
#Check
if grep -q "^HTTP/[12].* 200" "$RESPONSE_FILE"; then
print "DONE\n"
else
print "FAILED\n"
print "An error occurred requesting /upload\n"
ERROR_STATUS=1
return 1
fi
}
#Chunked file upload
#$1 = Local source file
#$2 = Remote destination file
db_chunked_upload_file() {
local file_src file_dst curl_parameters file_size offset upload_id upload_error chunk_params \
session_id chunk_number number_of_chunk
file_src=$(normalize_path "$1")
file_dst=$(normalize_path "$2")
if [[ $SHOW_PROGRESSBAR == 1 && $QUIET == 0 ]]; then
VERBOSE=1
curl_parameters="--progress-bar"
else
VERBOSE=0
curl_parameters="-L -s"
fi
file_size=$(file_size "$file_src")
offset=0
upload_id=""
upload_error=0
chunk_params=""
## Ceil division
((number_of_chunk = (file_size / 1024 / 1024 + CHUNK_SIZE - 1) / CHUNK_SIZE))
if [[ $VERBOSE == 1 ]]; then
print " > Uploading \"$file_src\" to \"$file_dst\" by $number_of_chunk chunks ...\n"
else
print " > Uploading \"$file_src\" to \"$file_dst\" by $number_of_chunk chunks "
fi
#Starting a new upload session
ensure_accesstoken
$CURL_BIN $CURL_ACCEPT_CERTIFICATES -X POST -L -s --show-error --globoff -i -o "$RESPONSE_FILE" --header "Authorization: Bearer $OAUTH_ACCESS_TOKEN" --header "Dropbox-API-Arg: {\"close\": false}" --header "Content-Type: application/octet-stream" --data-binary @/dev/null "$API_CHUNKED_UPLOAD_START_URL" 2>/dev/null
check_http_response $?
session_id=$(sed -n 's/{"session_id": *"*\([^"]*\)"*.*/\1/p' "$RESPONSE_FILE")
chunk_number=1
#Uploading chunks...
while [[ $offset != "$file_size" ]]; do
local offset_mb chunk_real_size
((offset_mb = offset / 1024 / 1024))
#Create the chunk
dd if="$file_src" of="$CHUNK_FILE" bs=1048576 skip="$offset_mb" count="$CHUNK_SIZE" 2>/dev/null
chunk_real_size=$(file_size "$CHUNK_FILE")
if [[ $VERBOSE == 1 ]]; then
print " >> Uploading chunk $chunk_number of $number_of_chunk\n"
fi
#Uploading the chunk...
echo >"$RESPONSE_FILE"
ensure_accesstoken
$CURL_BIN $CURL_ACCEPT_CERTIFICATES -X POST $curl_parameters --show-error --globoff -i -o "$RESPONSE_FILE" --header "Authorization: Bearer $OAUTH_ACCESS_TOKEN" --header "Dropbox-API-Arg: {\"cursor\": {\"session_id\": \"$session_id\",\"offset\": $offset},\"close\": false}" --header "Content-Type: application/octet-stream" --data-binary @"$CHUNK_FILE" "$API_CHUNKED_UPLOAD_APPEND_URL"
#check_http_response $? not needed, because we have to retry the request in case of error
#Check
if grep -q "^HTTP/[12].* 200" "$RESPONSE_FILE"; then
((offset = offset + chunk_real_size))
upload_error=0
if [[ $VERBOSE != 1 ]]; then
print "."
fi
((chunk_number = chunk_number + 1))
else
if [[ $VERBOSE != 1 ]]; then
print "*"
fi
((upload_error = upload_error + 1))
#On error, the upload is retried for max 3 times
if [[ $upload_error -gt 2 ]]; then
print " FAILED\n"
print "An error occurred requesting /chunked_upload\n"
ERROR_STATUS=1
return 1
fi
fi
done
upload_error=0
#Commit the upload
while (true); do
echo >"$RESPONSE_FILE"
ensure_accesstoken
$CURL_BIN $CURL_ACCEPT_CERTIFICATES -X POST -L -s --show-error --globoff -i -o "$RESPONSE_FILE" --header "Authorization: Bearer $OAUTH_ACCESS_TOKEN" --header "Dropbox-API-Arg: {\"cursor\": {\"session_id\": \"$session_id\",\"offset\": $offset},\"commit\": {\"path\": \"$file_dst\",\"mode\": \"overwrite\",\"autorename\": true,\"mute\": false}}" --header "Content-Type: application/octet-stream" --data-binary @/dev/null "$API_CHUNKED_UPLOAD_FINISH_URL" 2>/dev/null
#check_http_response $? not needed, because we have to retry the request in case of error
#Check
if grep -q "^HTTP/[12].* 200" "$RESPONSE_FILE"; then
upload_error=0
break
else
print "*"
((upload_error = upload_error + 1))
#On error, the commit is retried for max 3 times
if [[ $upload_error -gt 2 ]]; then
print " FAILED\n"
print "An error occurred requesting /commit_chunked_upload\n"
ERROR_STATUS=1
return 1
fi
fi
done
print " DONE\n"
}
#Directory upload
#$1 = Local source dir
#$2 = Remote destination dir
db_upload_dir() {
local dis_src dir_dst
dis_src=$(normalize_path "$1")
dir_dst=$(normalize_path "$2")
#Creatig remote directory
db_mkdir "$dir_dst"
for file in "$dis_src/"*; do
db_upload "$file" "$dir_dst"
done
}
#Generic download wrapper
#$1 = Remote source file/dir
#$2 = Local destination file/dir
db_download() {
local src dst dest_dir basedir out_file type src_req
src=$(normalize_path "$1")
dst=$(normalize_path "$2")
type=$(db_stat "$src")
#It's a directory
if [[ $type == "DIR" ]]; then
#If the dst folder is not specified, I assume that is the current directory
if [[ $dst == "" ]]; then
dst="."
fi
#Checking if the destination directory exists
if [[ ! -d $dst ]]; then
basedir=""
else
basedir=$(basename "$src")
fi
dest_dir=$(normalize_path "$dst/$basedir")
print " > Downloading folder \"$src\" to \"$dest_dir\"... \n"
if [[ ! -d "$dest_dir" ]]; then
print " > Creating local directory \"$dest_dir\"... "
mkdir -p "$dest_dir"
#Check
if [[ $? -eq 0 ]]; then
print "DONE\n"
else
print "FAILED\n"
ERROR_STATUS=1
return 1
fi
fi
if [[ $src == "/" ]]; then
src_req=""
else
src_req="$src"
fi
out_file=$(db_list_outfile "$src_req")
if [ $? -ne 0 ]; then
# When db_list_outfile fail, the error message is out_file
print "$out_file\n"
ERROR_STATUS=1
return 1
fi
#For each entry...
while read -r line; do
local file meta type size
file=${line%:*}
meta=${line##*:}
type=${meta%;*}
size=${meta#*;}
#Removing unneeded /
file=${file##*/}
if [[ $type == "file" ]]; then
db_download_file "$src/$file" "$dest_dir/$file"
elif [[ $type == "folder" ]]; then
db_download "$src/$file" "$dest_dir"
fi
done <"$out_file"
rm -fr "$out_file"
#It's a file
elif [[ $type == "FILE" ]]; then
#Checking dst
if [[ $dst == "" ]]; then
dst=$(basename "$src")
fi
#If the destination is a directory, the file will be download into
if [[ -d $dst ]]; then
dst="$dst/$src"
fi
db_download_file "$src" "$dst"
#Doesn't exists
else
print " > No such file or directory: $src\n"
ERROR_STATUS=1
return 1
fi
}
#Simple file download
#$1 = Remote source file
#$2 = Local destination file
db_download_file() {
local file_src file_dst curl_parameters line_cr
file_src=$(normalize_path "$1")
file_dst=$(normalize_path "$2")
if [[ $SHOW_PROGRESSBAR == 1 && $QUIET == 0 ]]; then
curl_parameters="-L --progress-bar"
line_cr="\n"
else
curl_parameters="-L -s"
line_cr=""
fi
#Checking if the file already exists
if [[ -e $file_dst && $SKIP_EXISTING_FILES == 1 ]]; then
print " > Skipping already existing file \"$file_dst\"\n"
return 1
fi
# Checking if the file has the correct check sum
type=$(db_stat "$file_dst")
if [[ $type != "ERR" ]]; then
local sha_src sha_dst
sha_src=$(db_sha "$file_src")
sha_dst=$(db_sha_local "$file_dst")
if [[ $sha_src == "$sha_dst" && $sha_src != "ERR" ]]; then
print "> Skipping file \"$file_src\", file exists with the same hash\n"
return 1
fi
fi
#Creating the empty file, that for two reasons:
#1) In this way I can check if the destination file is writable or not
#2) Curl doesn't automatically creates files with 0 bytes size
dd if=/dev/zero of="$file_dst" count=0 2>/dev/null
if [[ $? != 0 ]]; then
print " > Error writing file $file_dst: permission denied\n"
ERROR_STATUS=1
return 1
fi
print " > Downloading \"$file_src\" to \"$file_dst\"... $line_cr"
ensure_accesstoken
$CURL_BIN $CURL_ACCEPT_CERTIFICATES $curl_parameters -X POST --globoff -D "$RESPONSE_FILE" -o "$file_dst" --header "Authorization: Bearer $OAUTH_ACCESS_TOKEN" --header "Dropbox-API-Arg: {\"path\": \"$file_src\"}" "$API_DOWNLOAD_URL"
check_http_response $?
#Check
if grep -q "^HTTP/[12].* 200" "$RESPONSE_FILE"; then
print "DONE\n"
else
print "FAILED\n"
rm -fr "$file_dst"
ERROR_STATUS=1
return 1
fi
}
#Saveurl
#$1 = url
#$2 = Remote file destination
db_saveurl() {
local url file_dst file_name job_id
url="$1"
file_dst=$(normalize_path "$2")
file_name=$(basename "$url")
print " > Downloading \"$url\" to \"$file_dst\"..."
ensure_accesstoken
$CURL_BIN $CURL_ACCEPT_CERTIFICATES -X POST -L -s --show-error --globoff -i -o "$RESPONSE_FILE" --header "Authorization: Bearer $OAUTH_ACCESS_TOKEN" --header "Content-Type: application/json" --data "{\"path\": \"$file_dst/$file_name\", \"url\": \"$url\"}" "$API_SAVEURL_URL" 2>/dev/null
check_http_response $?
job_id=$(sed -n 's/.*"async_job_id": *"*\([^"]*\)"*.*/\1/p' "$RESPONSE_FILE")
if [[ $job_id == "" ]]; then
print " > Error getting the job id\n"
return 1
fi
#Checking the status
while (true); do
local status message
ensure_accesstoken
$CURL_BIN $CURL_ACCEPT_CERTIFICATES -X POST -L -s --show-error --globoff -i -o "$RESPONSE_FILE" --header "Authorization: Bearer $OAUTH_ACCESS_TOKEN" --header "Content-Type: application/json" --data "{\"async_job_id\": \"$job_id\"}" "$API_SAVEURL_JOBSTATUS_URL" 2>/dev/null
check_http_response $?
status=$(sed -n 's/{".tag": *"*\([^"]*\)"*.*/\1/p' "$RESPONSE_FILE")
case $status in
in_progress)
print "+"
;;
complete)
print " DONE\n"
break
;;
failed)
print " ERROR\n"
message=$(sed -n 's/.*"error_summary": *"*\([^"]*\)"*.*/\1/p' "$RESPONSE_FILE")
print " > Error: $message\n"
break
;;
esac
sleep 2
done
}
#Prints account info
db_account_info() {
print "Dropbox Uploader v$VERSION\n\n"
print " > Getting info... "
ensure_accesstoken
$CURL_BIN $CURL_ACCEPT_CERTIFICATES -X POST -L -s --show-error --globoff -i -o "$RESPONSE_FILE" --header "Authorization: Bearer $OAUTH_ACCESS_TOKEN" "$API_ACCOUNT_INFO_URL" 2>/dev/null
check_http_response $?
#Check
if grep -q "^HTTP/[12].* 200" "$RESPONSE_FILE"; then
local name uid email country
name=$(sed -n 's/.*"display_name": "\([^"]*\).*/\1/p' "$RESPONSE_FILE")
echo -e "\n\nName:\t\t$name"
uid=$(sed -n 's/.*"account_id": "\([^"]*\).*/\1/p' "$RESPONSE_FILE")
echo -e "UID:\t\t$uid"
email=$(sed -n 's/.*"email": "\([^"]*\).*/\1/p' "$RESPONSE_FILE")
echo -e "Email:\t\t$email"
country=$(sed -n 's/.*"country": "\([^"]*\).*/\1/p' "$RESPONSE_FILE")
echo -e "Country:\t$country"
echo ""
else
print "FAILED\n"
ERROR_STATUS=1
fi
}
#Prints account space usage info
db_account_space() {
print "Dropbox Uploader v$VERSION\n\n"
print " > Getting space usage info... "
ensure_accesstoken
$CURL_BIN $CURL_ACCEPT_CERTIFICATES -X POST -L -s --show-error --globoff -i -o "$RESPONSE_FILE" --header "Authorization: Bearer $OAUTH_ACCESS_TOKEN" "$API_ACCOUNT_SPACE_URL" 2>/dev/null
check_http_response $?
#Check
if grep -q "^HTTP/[12].* 200" "$RESPONSE_FILE"; then
local quota quota_mb used used_mb free_mb
quota=$(sed -n 's/.*"allocated": \([0-9]*\).*/\1/p' "$RESPONSE_FILE")
((quota_mb = quota / 1024 / 1024))
echo -e "\n\nQuota:\t$quota_mb Mb"
used=$(sed -n 's/.*"used": \([0-9]*\).*/\1/p' "$RESPONSE_FILE")
((used_mb = used / 1024 / 1024))
echo -e "Used:\t$used_mb Mb"
((free_mb = $((quota - used)) / 1024 / 1024))
echo -e "Free:\t$free_mb Mb"
echo ""
else
print "FAILED\n"
ERROR_STATUS=1
fi
}
#Account unlink
db_unlink() {
local answer
echo -ne "Are you sure you want unlink this script from your Dropbox account? [y/n]"
read -r answer
if [[ $answer == "y" ]]; then
rm -fr "$CONFIG_FILE"
OAUTH_APP_KEY=""
OAUTH_APP_SECRET=""
echo -ne "DONE\n"
echo -ne "\nDo you want to run the setup wizard? [y/N]: "
read -r answer
if [[ $answer == "y" ]]; then
db_configure
fi
fi
}
get_status_message() {
local retval
retval="$1"
if [[ "${retval}" -eq 0 ]]; then
echo " [ OK ]"
else
echo " [ FAILED ]"
# exit 1
fi
}
db_test() {
local temp_test_file_source temp_test_file_dest retval failed_count=0
echo -e " > Testing dropbox token permission ...\n"
temp_test_file_source="${TMP_DIR}/temp_test_file.$RANDOM.txt"
temp_test_file_dest="temp_test_file.$RANDOM.txt"
echo "This is a test file from ${SCRIPT_NAME} script. You can safely remove this file" >"${temp_test_file_source}"
echo -e " > Getting upload permission ...\n"
db_upload ${temp_test_file_source} /${temp_test_file_dest} >/dev/null 2>&1
retval=$?
[ "${retval}" -ne 0 ] && ((failed_count++))
get_status_message "${retval}"
echo ""
echo -e " > Getting download permission ...\n"
db_download /${temp_test_file_dest} ${temp_test_file_source} >/dev/null 2>&1
retval=$?
[ "${retval}" -ne 0 ] && ((failed_count++))
get_status_message "${retval}"
echo ""
echo -e " > Getting share permission ...\n"
db_share /${temp_test_file_dest} >/dev/null 2>&1
retval=$?
[ "${retval}" -ne 0 ] && ((failed_count++))
get_status_message "${retval}"
echo ""
echo -e " > Getting delete permission ...\n"
db_delete /${temp_test_file_dest} >/dev/null 2>&1
retval=$?
[ "${retval}" -ne 0 ] && ((failed_count++))
get_status_message "${retval}"
rm -f "${temp_test_file_source}"
if [[ $failed_count -gt 0 ]]; then
echo -e "\nError, one or more dropbox app permissions test failed"
echo -e "\nYou might want to run $(basename "$0") unlink and reconfigure the dropbox authentication"
else
echo -e "\nAll permissions are OK"
fi
exit "${failed_count}"
}
#Delete a remote file
#$1 = Remote file to delete
db_delete() {
local file_dst
file_dst=$(normalize_path "$1")
print " > Deleting \"$file_dst\"... "
ensure_accesstoken
$CURL_BIN $CURL_ACCEPT_CERTIFICATES -X POST -L -s --show-error --globoff -i -o "$RESPONSE_FILE" --header "Authorization: Bearer $OAUTH_ACCESS_TOKEN" --header "Content-Type: application/json" --data "{\"path\": \"$file_dst\"}" "$API_DELETE_URL" 2>/dev/null
check_http_response $?
#Check
if grep -q "^HTTP/[12].* 200" "$RESPONSE_FILE"; then
print "DONE\n"
else
print "FAILED\n"
ERROR_STATUS=1
return 1
fi
}
show_version() {
echo -e "Dropbox Uploader v$VERSION"
}
#Move/Rename a remote file
#$1 = Remote file to rename or move
#$2 = New file name or location
db_move() {
local file_src file_dst type
file_src=$(normalize_path "$1")
file_dst=$(normalize_path "$2")
type=$(db_stat "$file_dst")
#If the destination it's a directory, the source will be moved into it
if [[ $type == "DIR" ]]; then
local filename
filename=$(basename "$file_src")
file_dst=$(normalize_path "$file_dst/$filename")
fi
print " > Moving \"$file_src\" to \"$file_dst\" ... "
ensure_accesstoken
$CURL_BIN $CURL_ACCEPT_CERTIFICATES -X POST -L -s --show-error --globoff -i -o "$RESPONSE_FILE" --header "Authorization: Bearer $OAUTH_ACCESS_TOKEN" --header "Content-Type: application/json" --data "{\"from_path\": \"$file_src\", \"to_path\": \"$file_dst\"}" "$API_MOVE_URL" 2>/dev/null
check_http_response $?
#Check
if grep -q "^HTTP/[12].* 200" "$RESPONSE_FILE"; then
print "DONE\n"
else
print "FAILED\n"
ERROR_STATUS=1
return 1
fi
}
#Copy a remote file to a remote location
#$1 = Remote file to rename or move
#$2 = New file name or location
db_copy() {
local file_src file_dst type
file_src=$(normalize_path "$1")
file_dst=$(normalize_path "$2")
type=$(db_stat "$file_dst")
#If the destination it's a directory, the source will be copied into it
if [[ $type == "DIR" ]]; then
local filename
filename=$(basename "$file_src")
file_dst=$(normalize_path "$file_dst/$filename")
fi
print " > Copying \"$file_src\" to \"$file_dst\" ... "
ensure_accesstoken
$CURL_BIN $CURL_ACCEPT_CERTIFICATES -X POST -L -s --show-error --globoff -i -o "$RESPONSE_FILE" --header "Authorization: Bearer $OAUTH_ACCESS_TOKEN" --header "Content-Type: application/json" --data "{\"from_path\": \"$file_src\", \"to_path\": \"$file_dst\"}" "$API_COPY_URL" 2>/dev/null
check_http_response $?