-
Notifications
You must be signed in to change notification settings - Fork 144
/
gupload
executable file
·1698 lines (1550 loc) · 80.9 KB
/
gupload
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 sh
SELF_SOURCE="true"
# Functions that will used in core script
# posix functions
###################################################
# Convert bytes to human readable form
# Globals: None
# Required Arguments: 1
# ${1} = Positive integer ( bytes )
# Result: Print human readable form.
# Reference:
# https://unix.stackexchange.com/a/538015
###################################################
_bytes_to_human() {
b_bytes_to_human="$(printf "%.0f\n" "${1:-0}")" s_bytes_to_human=0
d_bytes_to_human='' type_bytes_to_human=''
while [ "${b_bytes_to_human}" -gt 1024 ]; do
d_bytes_to_human="$(printf ".%02d" $((b_bytes_to_human % 1024 * 100 / 1024)))"
b_bytes_to_human=$((b_bytes_to_human / 1024)) && s_bytes_to_human=$((s_bytes_to_human += 1))
done
j=0 && for i in B KB MB GB TB PB EB YB ZB; do
j="$((j += 1))" && [ "$((j - 1))" = "${s_bytes_to_human}" ] && type_bytes_to_human="${i}" && break
continue
done
printf "%s\n" "${b_bytes_to_human}${d_bytes_to_human} ${type_bytes_to_human}"
}
###################################################
# Check if debug is enabled and enable command trace
# Globals: 2 variables, 1 function
# Varibles - DEBUG, QUIET
# Function - _is_terminal
# Arguments: None
# Result: If DEBUG
# Present - Enable command trace and change print functions to avoid spamming.
# Absent - Disable command trace
# Check QUIET, then check terminal size and enable print functions accordingly.
###################################################
_check_debug() {
_print_center_quiet() { { [ $# = 3 ] && printf "%s\n" "${2}"; } || { printf "%s%s\n" "${2}" "${3}"; }; }
if [ -n "${DEBUG}" ]; then
set -x && PS4='-> '
_print_center() { { [ $# = 3 ] && printf "%s\n" "${2}"; } || { printf "%s%s\n" "${2}" "${3}"; }; }
_clear_line() { :; } && _newline() { :; }
else
if [ -z "${QUIET}" ]; then
# check if running in terminal and support ansi escape sequences
if _support_ansi_escapes; then
! COLUMNS="$(_get_columns_size)" || [ "${COLUMNS:-0}" -lt 45 ] 2>| /dev/null &&
_print_center() { { [ $# = 3 ] && printf "%s\n" "[ ${2} ]"; } || { printf "%s\n" "[ ${2}${3} ]"; }; }
export CURL_PROGRESS="-#" EXTRA_LOG="_print_center" CURL_PROGRESS_EXTRA="-#" SUPPORT_ANSI_ESCAPES="true"
else
_print_center() { { [ $# = 3 ] && printf "%s\n" "[ ${2} ]"; } || { printf "%s\n" "[ ${2}${3} ]"; }; }
_clear_line() { :; }
fi
_newline() { printf "%b" "${1}"; }
else
_print_center() { :; } && _clear_line() { :; } && _newline() { :; }
fi
set +x
fi
}
###################################################
# Check internet connection.
# Probably the fastest way, takes about 1 - 2 KB of data, don't check for more than 10 secs.
# Globals: 3 functions
# _print_center, _clear_line, _timeout
# Arguments: None
# Result: On
# Success - Nothing
# Error - print message and exit 1
###################################################
_check_internet() {
"${EXTRA_LOG}" "justify" "Checking Internet Connection.." "-"
if ! _timeout 10 curl -Is google.com --compressed; then
_clear_line 1
"${QUIET:-_print_center}" "justify" "Error: Internet connection" " not available." "="
exit 1
fi
_clear_line 1
}
###################################################
# Move cursor to nth no. of line and clear it to the begining.
# Globals: None
# Arguments: 1
# ${1} = Positive integer ( line number )
# Result: Read description
###################################################
_clear_line() {
printf "\e[%sA\e[2K" "${1}"
}
###################################################
# Alternative to dirname command
# Globals: None
# Arguments: 1
# ${1} = path of file or folder
# Result: read description
# Reference:
# https://github.com/dylanaraps/pure-sh-bible#file-paths
###################################################
_dirname() {
dir_dirname="${1:-.}"
dir_dirname="${dir_dirname%%"${dir_dirname##*[!/]}"}" && [ "${dir_dirname##*/*}" ] && dir_dirname=.
dir_dirname="${dir_dirname%/*}" && dir_dirname="${dir_dirname%%"${dir_dirname##*[!/]}"}"
printf '%s\n' "${dir_dirname:-/}"
}
###################################################
# Convert given time in seconds to readable form
# 110 to 1 minute(s) and 50 seconds
# Globals: None
# Arguments: 1
# ${1} = Positive Integer ( time in seconds )
# Result: read description
# Reference:
# https://stackoverflow.com/a/32164707
###################################################
_display_time() {
t_display_time="${1}" day_display_time="$((t_display_time / 60 / 60 / 24))"
hr_display_time="$((t_display_time / 60 / 60 % 24))" min_display_time="$((t_display_time / 60 % 60))" sec_display_time="$((t_display_time % 60))"
[ "${day_display_time}" -gt 0 ] && printf '%d days ' "${day_display_time}"
[ "${hr_display_time}" -gt 0 ] && printf '%d hrs ' "${hr_display_time}"
[ "${min_display_time}" -gt 0 ] && printf '%d minute(s) ' "${min_display_time}"
[ "${day_display_time}" -gt 0 ] || [ "${hr_display_time}" -gt 0 ] || [ "${min_display_time}" -gt 0 ] && printf 'and '
printf '%d seconds\n' "${sec_display_time}"
}
###################################################
# print column size
# use zsh or stty or tput
###################################################
_get_columns_size() {
{ command -v bash 1>| /dev/null && bash -c 'shopt -s checkwinsize && (: && :); printf "%s\n" "${COLUMNS}" 2>&1'; } ||
{ command -v zsh 1>| /dev/null && zsh -c 'printf "%s\n" "${COLUMNS}"'; } ||
{ command -v stty 1>| /dev/null && _tmp="$(stty size)" && printf "%s\n" "${_tmp##* }"; } ||
{ command -v tput 1>| /dev/null && tput cols; } ||
return 1
}
###################################################
# Fetch latest commit sha of release or branch
# Do not use github rest api because rate limit error occurs
# Globals: None
# Arguments: 3
# ${1} = "branch" or "release"
# ${2} = branch name or release name
# ${3} = repo name e.g labbots/google-drive-upload
# Result: print fetched sha
###################################################
_get_latest_sha() {
unset latest_sha_get_latest_sha raw_get_latest_sha
case "${1:-${TYPE}}" in
branch)
latest_sha_get_latest_sha="$(
raw_get_latest_sha="$(curl --compressed -s https://github.com/"${3:-${REPO}}"/commits/"${2:-${TYPE_VALUE}}".atom -r 0-2000)"
_tmp="$(printf "%s\n" "${raw_get_latest_sha}" | grep -o "Commit\\/.*<" -m1 || :)" && _tmp="${_tmp##*\/}" && printf "%s\n" "${_tmp%%<*}"
)"
;;
release)
latest_sha_get_latest_sha="$(
raw_get_latest_sha="$(curl -L --compressed -s https://github.com/"${3:-${REPO}}"/releases/"${2:-${TYPE_VALUE}}")"
_tmp="$(printf "%s\n" "${raw_get_latest_sha}" | grep "=\"/""${3:-${REPO}}""/commit" -m1 || :)" && _tmp="${_tmp##*commit\/}" && printf "%s\n" "${_tmp%%\"*}"
)"
;;
esac
printf "%b" "${latest_sha_get_latest_sha:+${latest_sha_get_latest_sha}\n}"
}
###################################################
# Method to extract specified field data from json
# Globals: None
# Arguments: 2
# ${1} - value of field to fetch from json
# ${2} - Optional, no of lines to parse for the given field in 1st arg
# ${3} - Optional, nth number of value from extracted values, default it 1.
# Input: file | pipe
# _json_value "Arguments" < file
# echo something | _json_value "Arguments"
# Result: print extracted value
###################################################
_json_value() {
{ [ "${2}" -gt 0 ] 2>| /dev/null && no_of_lines_json_value="${2}"; } || :
{ [ "${3}" -gt 0 ] 2>| /dev/null && num_json_value="${3}"; } || { ! [ "${3}" = all ] && num_json_value=1; }
# shellcheck disable=SC2086
_tmp="$(grep -o "\"${1}\"\:.*" ${no_of_lines_json_value:+-m} ${no_of_lines_json_value})" || return 1
printf "%s\n" "${_tmp}" | sed -e "s/.*\"""${1}""\"://" -e 's/[",]*$//' -e 's/["]*$//' -e 's/[,]*$//' -e "s/^ //" -e 's/^"//' -n -e "${num_json_value}"p || :
return 0
}
###################################################
# Print a text to center interactively and fill the rest of the line with text specified.
# This function is fine-tuned to this script functionality, so may appear unusual.
# Globals: 1 variable
# COLUMNS
# Arguments: 4
# If ${1} = normal
# ${2} = text to print
# ${3} = symbol
# If ${1} = justify
# If remaining arguments = 2
# ${2} = text to print
# ${3} = symbol
# If remaining arguments = 3
# ${2}, ${3} = text to print
# ${4} = symbol
# Result: read description
# Reference:
# https://gist.github.com/TrinityCoder/911059c83e5f7a351b785921cf7ecda
###################################################
_print_center() {
[ $# -lt 3 ] && printf "Missing arguments\n" && return 1
term_cols_print_center="${COLUMNS}"
type_print_center="${1}" filler_print_center=""
case "${type_print_center}" in
normal) out_print_center="${2}" && symbol_print_center="${3}" ;;
justify)
if [ $# = 3 ]; then
input1_print_center="${2}" symbol_print_center="${3}" to_print_print_center="" out_print_center=""
to_print_print_center="$((term_cols_print_center - 5))"
{ [ "${#input1_print_center}" -gt "${to_print_print_center}" ] && out_print_center="[ $(printf "%.${to_print_print_center}s\n" "${input1_print_center}")..]"; } ||
{ out_print_center="[ ${input1_print_center} ]"; }
else
input1_print_center="${2}" input2_print_center="${3}" symbol_print_center="${4}" to_print_print_center="" temp_print_center="" out_print_center=""
to_print_print_center="$((term_cols_print_center * 47 / 100))"
{ [ "${#input1_print_center}" -gt "${to_print_print_center}" ] && temp_print_center=" $(printf "%.${to_print_print_center}s\n" "${input1_print_center}").."; } ||
{ temp_print_center=" ${input1_print_center}"; }
to_print_print_center="$((term_cols_print_center * 46 / 100))"
{ [ "${#input2_print_center}" -gt "${to_print_print_center}" ] && temp_print_center="${temp_print_center}$(printf "%.${to_print_print_center}s\n" "${input2_print_center}").. "; } ||
{ temp_print_center="${temp_print_center}${input2_print_center} "; }
out_print_center="[${temp_print_center}]"
fi
;;
*) return 1 ;;
esac
str_len_print_center="${#out_print_center}"
[ "${str_len_print_center}" -ge "$((term_cols_print_center - 1))" ] && {
printf "%s\n" "${out_print_center}" && return 0
}
filler_print_center_len="$(((term_cols_print_center - str_len_print_center) / 2))"
i_print_center=1 && while [ "${i_print_center}" -le "${filler_print_center_len}" ]; do
filler_print_center="${filler_print_center}${symbol_print_center}" && i_print_center="$((i_print_center + 1))"
done
printf "%s%s%s" "${filler_print_center}" "${out_print_center}" "${filler_print_center}"
[ "$(((term_cols_print_center - str_len_print_center) % 2))" -ne 0 ] && printf "%s" "${symbol_print_center}"
printf "\n"
return 0
}
###################################################
# Check if script terminal supports ansi escapes
# Globals: 1 variable
# TERM
# Arguments: None
# Result: return 1 or 0
###################################################
_support_ansi_escapes() {
unset ansi_escapes
case "${TERM}" in
xterm* | rxvt* | urxvt* | linux* | vt* | screen*) ansi_escapes="true" ;;
esac
{ [ -t 2 ] && [ -n "${ansi_escapes}" ] && return 0; } || return 1
}
###################################################
# Alternative to timeout command
# Globals: None
# Arguments: 1 and rest
# ${1} = amount of time to sleep
# rest = command to execute
# Result: Read description
# Reference:
# https://stackoverflow.com/a/24416732
###################################################
_timeout() {
timeout_timeout="${1:?Error: Specify Timeout}" && shift
{
"${@}" &
child="${!}"
trap -- "" TERM
{
sleep "${timeout_timeout}"
kill -9 "${child}"
} &
wait "${child}"
} 2>| /dev/null 1>&2
}
###################################################
# Config updater
# Incase of old value, update, for new value add.
# Globals: None
# Arguments: 3
# ${1} = value name
# ${2} = value
# ${3} = config path
# Result: read description
###################################################
_update_config() {
[ $# -lt 3 ] && printf "Missing arguments\n" && return 1
value_name_update_config="${1}" value_update_config="${2}" config_path_update_config="${3}"
! [ -f "${config_path_update_config}" ] && : >| "${config_path_update_config}" # If config file doesn't exist.
chmod u+w "${config_path_update_config}"
printf "%s\n%s\n" "$(grep -v -e "^$" -e "^${value_name_update_config}=" "${config_path_update_config}" || :)" \
"${value_name_update_config}=\"${value_update_config}\"" >| "${config_path_update_config}"
chmod u-w+r "${config_path_update_config}"
}
###################################################
# Encode the given string to parse properly in network requests
# Globals: None
# Arguments: 1
# ${1} = string
# Result: print encoded string
# Reference:
# https://stackoverflow.com/a/41405682
###################################################
_url_encode() (
LC_ALL=C LANG=C
awk 'BEGIN {while (y++ < 125) z[sprintf("%c", y)] = y
while (y = substr(ARGV[1], ++j, 1))
q = y ~ /[[:alnum:]]_.!~*\47()-]/ ? q y : q sprintf("%%%02X", z[y])
print q}' "${1}"
)
###################################################
# Search for an existing file on gdrive with write permission.
# Globals: 3 variables, 2 functions
# Variables - API_URL, API_VERSION, ACCESS_TOKEN
# Functions - _url_encode, _json_value
# Arguments: 2
# ${1} = file name
# ${2} = root dir id of file
# Result: print file id else blank
# Reference:
# https://developers.google.com/drive/api/v3/search-files
###################################################
_check_existing_file() (
[ $# -lt 2 ] && printf "Missing arguments\n" && return 1
name_check_existing_file="${1##*/}" rootdir_check_existing_file="${2}"
unset query_check_existing_file response_check_existing_file id_check_existing_file
"${EXTRA_LOG}" "justify" "Checking if file" " exists on gdrive.." "-" 1>&2
query_check_existing_file="$(_url_encode "name='${name_check_existing_file}' and '${rootdir_check_existing_file}' in parents and trashed=false and 'me' in writers")"
response_check_existing_file="$(_api_request "${CURL_PROGRESS_EXTRA}" \
"${API_URL}/drive/${API_VERSION}/files?q=${query_check_existing_file}&fields=files(id,name,mimeType)&supportsAllDrives=true&includeItemsFromAllDrives=true" || :)" && _clear_line 1 1>&2
_clear_line 1 1>&2
{ printf "%s\n" "${response_check_existing_file}" | _json_value id 1 1 2>| /dev/null 1>&2 && printf "%s\n" "${response_check_existing_file}"; } || return 1
return 0
)
###################################################
# Copy/Clone a public gdrive file/folder from another/same gdrive account
# Globals: 6 variables, 2 functions
# Variables - API_URL, API_VERSION, CURL_PROGRESS, LOG_FILE_ID, QUIET, ACCESS_TOKEN
# Functions - _print_center, _check_existing_file, _json_value, _bytes_to_human, _clear_line
# Arguments: 5
# ${1} = update or upload ( upload type )
# ${2} = file id to upload
# ${3} = root dir id for file
# ${4} = name of file
# ${5} = size of file
# Result: On
# Success - Upload/Update file and export FILE_ID
# Error - return 1
# Reference:
# https://developers.google.com/drive/api/v2/reference/files/copy
###################################################
_clone_file() {
[ $# -lt 5 ] && printf "Missing arguments\n" && return 1
job_clone_file="${1}" file_id_clone_file="${2}" file_root_id_clone_file="${3}" name_clone_file="${4}" size_clone_file="${5}"
unset post_data_clone_file response_clone_file readable_size_clone_file && STRING="Cloned"
post_data_clone_file="{\"parents\": [\"${file_root_id_clone_file}\"]}"
readable_size_clone_file="$(printf "%s\n" "${size_clone_file}" | _bytes_to_human)"
_print_center "justify" "${name_clone_file} " "| ${readable_size_clone_file}" "="
if [ "${job_clone_file}" = update ]; then
unset file_check_json_clone_file
# Check if file actually exists.
if file_check_json_clone_file="$(_check_existing_file "${name_clone_file}" "${file_root_id_clone_file}")"; then
if [ -n "${SKIP_DUPLICATES}" ]; then
_collect_file_info "${file_check_json_clone_file}" "${name_clone_file}" || return 1
_clear_line 1
"${QUIET:-_print_center}" "justify" "${name_clone_file}" " already exists." "=" && return 0
else
_print_center "justify" "Overwriting file.." "-"
{ _file_id_clone_file="$(printf "%s\n" "${file_check_json_clone_file}" | _json_value id 1 1)" &&
post_data_clone_file="$(_drive_info "${_file_id_clone_file}" "parents,writersCanShare")"; } ||
{ _error_logging_upload "${name_clone_file}" "${post_data_clone_file:-${file_check_json_clone_file}}"; }
if [ "${_file_id_clone_file}" != "${file_id_clone_file}" ]; then
_api_request -s \
-X DELETE \
"${API_URL}/drive/${API_VERSION}/files/${_file_id_clone_file}?supportsAllDrives=true&includeItemsFromAllDrives=true" 2>| /dev/null 1>&2 || :
STRING="Updated"
else
_collect_file_info "${file_check_json_clone_file}" "${name_clone_file}" || return 1
fi
fi
else
_print_center "justify" "Cloning file.." "-"
fi
else
_print_center "justify" "Cloning file.." "-"
fi
# shellcheck disable=SC2086
response_clone_file="$(_api_request ${CURL_PROGRESS} \
-X POST \
-H "Content-Type: application/json; charset=UTF-8" \
-d "${post_data_clone_file}" \
"${API_URL}/drive/${API_VERSION}/files/${file_id_clone_file}/copy?supportsAllDrives=true&includeItemsFromAllDrives=true" || :)"
for _ in 1 2 3; do _clear_line 1; done
_collect_file_info "${response_clone_file}" "${name_clone_file}" || return 1
"${QUIET:-_print_center}" "justify" "${name_clone_file} " "| ${readable_size_clone_file} | ${STRING}" "="
return 0
}
###################################################
# Create/Check directory in google drive.
# Globals: 3 variables, 2 functions
# Variables - API_URL, API_VERSION, ACCESS_TOKEN
# Functions - _url_encode, _json_value
# Arguments: 2
# ${1} = dir name
# ${2} = root dir id of given dir
# Result: print folder id
# Reference:
# https://developers.google.com/drive/api/v3/folder
###################################################
_create_directory() {
[ $# -lt 2 ] && printf "Missing arguments\n" && return 1
dirname_create_directory="${1##*/}" rootdir_create_directory="${2}"
unset query_create_directory search_response_create_directory folder_id_create_directory
"${EXTRA_LOG}" "justify" "Creating GDRIVE DIR:" " ${dirname_create_directory}" "-" 1>&2
query_create_directory="$(_url_encode "mimeType='application/vnd.google-apps.folder' and name='${dirname_create_directory}' and trashed=false and '${rootdir_create_directory}' in parents")"
search_response_create_directory="$(_api_request "${CURL_PROGRESS_EXTRA}" \
"${API_URL}/drive/${API_VERSION}/files?q=${query_create_directory}&fields=files(id)&supportsAllDrives=true&includeItemsFromAllDrives=true" || :)" && _clear_line 1 1>&2
if ! folder_id_create_directory="$(printf "%s\n" "${search_response_create_directory}" | _json_value id 1 1)"; then
unset create_folder_post_data_create_directory create_folder_response_create_directory
create_folder_post_data_create_directory="{\"mimeType\": \"application/vnd.google-apps.folder\",\"name\": \"${dirname_create_directory}\",\"parents\": [\"${rootdir_create_directory}\"]}"
create_folder_response_create_directory="$(_api_request "${CURL_PROGRESS_EXTRA}" \
-X POST \
-H "Content-Type: application/json; charset=UTF-8" \
-d "${create_folder_post_data_create_directory}" \
"${API_URL}/drive/${API_VERSION}/files?fields=id&supportsAllDrives=true&includeItemsFromAllDrives=true" || :)" && _clear_line 1 1>&2
fi
_clear_line 1 1>&2
{ folder_id_create_directory="${folder_id_create_directory:-$(printf "%s\n" "${create_folder_response_create_directory}" | _json_value id 1 1)}" && printf "%s\n" "${folder_id_create_directory}"; } ||
{ printf "%s\n" "${create_folder_response_create_directory}" 1>&2 && return 1; }
return 0
}
###################################################
# Get information for a gdrive folder/file.
# Globals: 3 variables, 1 function
# Variables - API_URL, API_VERSION, ACCESS_TOKEN
# Functions - _json_value
# Arguments: 2
# ${1} = folder/file gdrive id
# ${2} = information to fetch, e.g name, id
# Result: On
# Success - print fetched value
# Error - print "message" field from the json
# Reference:
# https://developers.google.com/drive/api/v3/search-files
###################################################
_drive_info() {
[ $# -lt 2 ] && printf "Missing arguments\n" && return 1
folder_id_drive_info="${1}" fetch_drive_info="${2}"
unset search_response_drive_info
"${EXTRA_LOG}" "justify" "Fetching info.." "-" 1>&2
search_response_drive_info="$(_api_request "${CURL_PROGRESS_EXTRA}" \
"${API_URL}/drive/${API_VERSION}/files/${folder_id_drive_info}?fields=${fetch_drive_info}&supportsAllDrives=true&includeItemsFromAllDrives=true" || :)" && _clear_line 1 1>&2
_clear_line 1 1>&2
printf "%b" "${search_response_drive_info:+${search_response_drive_info}\n}"
return 0
}
###################################################
# Extract ID from a googledrive folder/file url.
# Globals: None
# Arguments: 1
# ${1} = googledrive folder/file url.
# Result: print extracted ID
###################################################
_extract_id() {
[ $# = 0 ] && printf "Missing arguments\n" && return 1
LC_ALL=C id_extract_id="${1}"
case "${id_extract_id}" in
*'drive.google.com'*'id='*) _tmp="${id_extract_id##*id=}" && _tmp="${_tmp%%\?*}" && id_extract_id="${_tmp%%\&*}" ;;
*'drive.google.com'*'file/d/'* | 'http'*'docs.google.com'*'/d/'*) _tmp="${id_extract_id##*\/d\/}" && _tmp="${_tmp%%\/*}" && _tmp="${_tmp%%\?*}" && id_extract_id="${_tmp%%\&*}" ;;
*'drive.google.com'*'drive'*'folders'*) _tmp="${id_extract_id##*\/folders\/}" && _tmp="${_tmp%%\?*}" && id_extract_id="${_tmp%%\&*}" ;;
esac
printf "%b" "${id_extract_id:+${id_extract_id}\n}"
}
###################################################
# Method to regenerate access_token ( also updates in config ).
# Make a request on https://www.googleapis.com/oauth2/""${API_VERSION}""/tokeninfo?access_token=${ACCESS_TOKEN} url and check if the given token is valid, if not generate one.
# Globals: 9 variables, 2 functions
# Variables - CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, TOKEN_URL, CONFIG, API_URL, API_VERSION, QUIET, NO_UPDATE_TOKEN
# Functions - _update_config and _print_center
# Result: Update access_token and expiry else print error
###################################################
_get_access_token_and_update() {
RESPONSE="${1:-$(curl --compressed -s -X POST --data "client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&refresh_token=${REFRESH_TOKEN}&grant_type=refresh_token" "${TOKEN_URL}")}" || :
if ACCESS_TOKEN="$(printf "%s\n" "${RESPONSE}" | _json_value access_token 1 1)"; then
ACCESS_TOKEN_EXPIRY="$(($(date +"%s") + $(printf "%s\n" "${RESPONSE}" | _json_value expires_in 1 1) - 1))"
_update_config ACCESS_TOKEN "${ACCESS_TOKEN}" "${CONFIG}"
_update_config ACCESS_TOKEN_EXPIRY "${ACCESS_TOKEN_EXPIRY}" "${CONFIG}"
else
"${QUIET:-_print_center}" "justify" "Error: Something went wrong" ", printing error." "=" 1>&2
printf "%s\n" "${RESPONSE}" 1>&2
return 1
fi
return 0
}
###################################################
# Upload ( Create/Update ) files on gdrive.
# Interrupted uploads can be resumed.
# Globals: 8 variables, 10 functions
# Variables - API_URL, API_VERSION, QUIET, VERBOSE, VERBOSE_PROGRESS, CURL_PROGRESS, LOG_FILE_ID, ACCESS_TOKEN
# Functions - _url_encode, _json_value, _print_center, _bytes_to_human
# _generate_upload_link, _upload_file_from_uri, _log_upload_session, _remove_upload_session
# _full_upload, _collect_file_info
# Arguments: 3
# ${1} = update or upload ( upload type )
# ${2} = file to upload
# ${3} = root dir id for file
# Result: On
# Success - Upload/Update file and export FILE_ID
# Error - return 1
# Reference:
# https://developers.google.com/drive/api/v3/create-file
# https://developers.google.com/drive/api/v3/manage-uploads
# https://developers.google.com/drive/api/v3/reference/files/update
###################################################
_upload_file() {
[ $# -lt 3 ] && printf "Missing arguments\n" && return 1
job_upload_file="${1}" input_upload_file="${2}" folder_id_upload_file="${3}"
unset slug_upload_file inputname_upload_file extension_upload_file inputsize_upload_file readable_size_upload_file request_method_upload_file \
url_upload_file postdata_upload_file uploadlink_upload_file upload_body_upload_file mime_type_upload_file resume_args_upload_file
slug_upload_file="${input_upload_file##*/}"
inputname_upload_file="${slug_upload_file%.*}"
extension_upload_file="${slug_upload_file##*.}"
inputsize_upload_file="$(($(wc -c < "${input_upload_file}")))" && content_length_upload_file="${inputsize_upload_file}"
readable_size_upload_file="$(printf "%s\n" "${inputsize_upload_file}" | _bytes_to_human)"
# Handle extension-less files
[ "${inputname_upload_file}" = "${extension_upload_file}" ] && {
mime_type_upload_file="$(file --brief --mime-type "${input_upload_file}" || mimetype --output-format %m "${input_upload_file}")" 2>| /dev/null || {
"${QUIET:-_print_center}" "justify" "Error: file or mimetype command not found." "=" && printf "\n"
exit 1
}
}
_print_center "justify" "${slug_upload_file}" " | ${readable_size_upload_file}" "="
# Set proper variables for overwriting files
[ "${job_upload_file}" = update ] && {
unset file_check_json_upload_file
# Check if file actually exists, and create if not.
if file_check_json_upload_file="$(_check_existing_file "${slug_upload_file}" "${folder_id_upload_file}")"; then
if [ -n "${SKIP_DUPLICATES}" ]; then
# Stop upload if already exists ( -d/--skip-duplicates )
_collect_file_info "${file_check_json_upload_file}" "${slug_upload_file}" || return 1
_clear_line 1
"${QUIET:-_print_center}" "justify" "${slug_upload_file} already exists." "=" && return 0
else
request_method_upload_file="PATCH"
_file_id_upload_file="$(printf "%s\n" "${file_check_json_upload_file}" | _json_value id 1 1)" || { _error_logging_upload "${slug_upload_file}" "${file_check_json_upload_file}"; }
url_upload_file="${API_URL}/upload/drive/${API_VERSION}/files/${_file_id_upload_file}?uploadType=resumable&supportsAllDrives=true&includeItemsFromAllDrives=true"
# JSON post data to specify the file name and folder under while the file to be updated
postdata_upload_file="{\"mimeType\": \"${mime_type_upload_file}\",\"name\": \"${slug_upload_file}\",\"addParents\": [\"${folder_id_upload_file}\"]}"
STRING="Updated"
fi
else
job_upload_file="create"
fi
}
# Set proper variables for creating files
[ "${job_upload_file}" = create ] && {
url_upload_file="${API_URL}/upload/drive/${API_VERSION}/files?uploadType=resumable&supportsAllDrives=true&includeItemsFromAllDrives=true"
request_method_upload_file="POST"
# JSON post data to specify the file name and folder under while the file to be created
postdata_upload_file="{\"mimeType\": \"${mime_type_upload_file}\",\"name\": \"${slug_upload_file}\",\"parents\": [\"${folder_id_upload_file}\"]}"
STRING="Uploaded"
}
__file_upload_file="${INFO_PATH}/${slug_upload_file}__::__${folder_id_upload_file}__::__${inputsize_upload_file}"
# https://developers.google.com/drive/api/v3/manage-uploads
if [ -r "${__file_upload_file}" ]; then
uploadlink_upload_file="$(cat "${__file_upload_file}" || :)"
http_code_upload_file="$(curl --compressed -s -X PUT "${uploadlink_upload_file}" -o /dev/null --write-out %"{http_code}")" || :
case "${http_code_upload_file}" in
308) # Active Resumable URI give 308 status
uploaded_range_upload_file="$(raw_upload_file="$(curl --compressed -s -X PUT \
-H "Content-Range: bytes */${content_length_upload_file}" \
--url "${uploadlink_upload_file}" --globoff -D - || :)" &&
printf "%s\n" "${raw_upload_file##*[R,r]ange: bytes=0-}" | while read -r line; do printf "%s\n" "${line%%$(printf '\r')}" && break; done)"
if [ "${uploaded_range_upload_file}" -gt 0 ] 2>| /dev/null; then
_print_center "justify" "Resuming interrupted upload.." "-" && _newline "\n"
content_range_upload_file="$(printf "bytes %s-%s/%s\n" "$((uploaded_range_upload_file + 1))" "$((inputsize_upload_file - 1))" "${inputsize_upload_file}")"
content_length_upload_file="$((inputsize_upload_file - $((uploaded_range_upload_file + 1))))"
# Resuming interrupted uploads needs http1.1
resume_args1='-s' resume_args2='--http1.1' resume_args3="Content-Range: ${content_range_upload_file}"
_upload_file_from_uri _clear_line
_collect_file_info "${upload_body_upload_file}" "${slug_upload_file}" || return 1
_normal_logging_upload
_remove_upload_session
else
_full_upload || return 1
fi
;;
4[0-9][0-9] | 000) # Dead Resumable URI give 40* status
_full_upload || return 1
;;
201 | 200) # Completed Resumable URI give 20* status
upload_body_upload_file="${http_code_upload_file}"
_collect_file_info "${upload_body_upload_file}" "${slug_upload_file}" || return 1
_normal_logging_upload
_remove_upload_session
;;
esac
else
_full_upload || return 1
fi
return 0
}
###################################################
# Sub functions for _upload_file function - Start
# generate resumable upload link
_generate_upload_link() {
"${EXTRA_LOG}" "justify" "Generating upload link.." "-" 1>&2
uploadlink_upload_file="$(_api_request "${CURL_PROGRESS_EXTRA}" \
-X "${request_method_upload_file}" \
-H "Content-Type: application/json; charset=UTF-8" \
-H "X-Upload-Content-Type: ${mime_type_upload_file}" \
-H "X-Upload-Content-Length: ${inputsize_upload_file}" \
-d "$postdata_upload_file" \
"${url_upload_file}" \
-D - || :)" && _clear_line 1 1>&2
_clear_line 1 1>&2
case "${uploadlink_upload_file}" in
*'ocation: '*'upload_id'*) uploadlink_upload_file="$(printf "%s\n" "${uploadlink_upload_file##*[L,l]ocation: }" | while read -r line; do printf "%s\n" "${line%%$(printf '\r')}" && break; done)" && return 0 ;;
'' | *) return 1 ;;
esac
return 0
}
# Curl command to push the file to google drive.
_upload_file_from_uri() {
_print_center "justify" "Uploading.." "-"
# shellcheck disable=SC2086 # Because unnecessary to another check because ${CURL_PROGRESS} won't be anything problematic.
upload_body_upload_file="$(_api_request ${CURL_PROGRESS} \
-X PUT \
-H "Content-Type: ${mime_type_upload_file}" \
-H "Content-Length: ${content_length_upload_file}" \
-H "Slug: ${slug_upload_file}" \
-T "${input_upload_file}" \
-o- \
--url "${uploadlink_upload_file}" \
--globoff \
${CURL_SPEED} ${resume_args1} ${resume_args2} \
-H "${resume_args3}" || :)"
[ -z "${VERBOSE_PROGRESS}" ] && for _ in 1 2; do _clear_line 1; done && "${1:-:}"
return 0
}
# logging in case of successful upload
_normal_logging_upload() {
[ -z "${VERBOSE_PROGRESS}" ] && _clear_line 1
"${QUIET:-_print_center}" "justify" "${slug_upload_file} " "| ${readable_size_upload_file} | ${STRING}" "="
return 0
}
# Tempfile Used for resuming interrupted uploads
_log_upload_session() {
[ "${inputsize_upload_file}" -gt 1000000 ] && printf "%s\n" "${uploadlink_upload_file}" >| "${__file_upload_file}"
return 0
}
# remove upload session
_remove_upload_session() {
rm -f "${__file_upload_file}"
return 0
}
# wrapper to fully upload a file from scratch
_full_upload() {
_generate_upload_link || { _error_logging_upload "${slug_upload_file}" "${uploadlink_upload_file}"; }
_log_upload_session
_upload_file_from_uri
_collect_file_info "${upload_body_upload_file}" "${slug_upload_file}" || return 1
_normal_logging_upload
_remove_upload_session
return 0
}
# Sub functions for _upload_file function - End
###################################################
###################################################
# Share a gdrive file/folder
# Globals: 3 variables, 4 functions
# Variables - API_URL, API_VERSION, ACCESS_TOKEN
# Functions - _url_encode, _json_value, _print_center, _clear_line
# Arguments: 2
# ${1} = gdrive ID of folder/file
# ${2} = Email to which file will be shared ( optional )
# Result: read description
# Reference:
# https://developers.google.com/drive/api/v3/manage-sharing
###################################################
_share_id() {
[ $# -lt 2 ] && printf "Missing arguments\n" && return 1
id_share_id="${1}" share_email_share_id="${2}" role_share_id="reader" type_share_id="${share_email_share_id:+user}"
unset post_data_share_id response_share_id
"${EXTRA_LOG}" "justify" "Sharing.." "-" 1>&2
post_data_share_id="{\"role\":\"${role_share_id}\",\"type\":\"${type_share_id:-anyone}\"${share_email_share_id:+,\\\"emailAddress\\\":\\\"${share_email_share_id}\\\"}}"
response_share_id="$(_api_request "${CURL_PROGRESS_EXTRA}" \
-X POST \
-H "Content-Type: application/json; charset=UTF-8" \
-d "${post_data_share_id}" \
"${API_URL}/drive/${API_VERSION}/files/${id_share_id}/permissions?supportsAllDrives=true&includeItemsFromAllDrives=true" || :)" && _clear_line 1 1>&2
_clear_line 1 1>&2
{ printf "%s\n" "${response_share_id}" | _json_value id 1 1 2>| /dev/null 1>&2 && return 0; } ||
{ printf "%s\n" "Error: Cannot Share." 1>&2 && printf "%s\n" "${response_share_id}" 1>&2 && return 1; }
}
# shellcheck source=/dev/null
###################################################
# A simple wrapper to check tempfile for access token and make authorized oauth requests to drive api
###################################################
_api_request() {
. "${TMPFILE}_ACCESS_TOKEN"
curl --compressed \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
"${@}"
}
###################################################
# Used in collecting file properties from output json after a file has been uploaded/cloned
# Also handles logging in log file if LOG_FILE_ID is set
# Globals: 1 variables, 2 functions
# Variables - LOG_FILE_ID
# Functions - _error_logging_upload, _json_value
# Arguments: 1
# ${1} = output jsom
# Result: set fileid and link, save info to log file if required
###################################################
_collect_file_info() {
json_collect_file_info="${1}" info_collect_file_info=""
FILE_ID="$(printf "%s\n" "${json_collect_file_info}" | _json_value id 1 1)" || { _error_logging_upload "${2}" "${json_collect_file_info}"; }
{ [ -z "${LOG_FILE_ID}" ] || [ -d "${LOG_FILE_ID}" ]; } && return 0
info_collect_file_info="Link: https://drive.google.com/open?id=${FILE_ID}
Name: $(printf "%s\n" "${json_collect_file_info}" | _json_value name 1 1 || :)
ID: ${FILE_ID}
Type: $(printf "%s\n" "${json_collect_file_info}" | _json_value mimeType 1 1 || :)"
printf "%s\n\n" "${info_collect_file_info}" >> "${LOG_FILE_ID}"
return 0
}
###################################################
# Error logging wrapper
###################################################
_error_logging_upload() {
log_error_logging_upload="${2}"
"${QUIET:-_print_center}" "justify" "Upload ERROR" ", ${1:-} not ${STRING:-uploaded}." "=" 1>&2
case "${log_error_logging_upload}" in
# https://github.com/rclone/rclone/issues/3857#issuecomment-573413789
*'"message": "User rate limit exceeded."'*)
printf "%s\n\n%s\n" "${log_error_logging_upload}" \
"Today's upload limit reached for this account. Use another account to upload or wait for tomorrow." 1>&2
# Never retry if upload limit reached
export RETRY=0
;;
'' | *) printf "%s\n" "${log_error_logging_upload}" 1>&2 ;;
esac
printf "\n\n\n" 1>&2
return 1
}
###################################################
# A small function to get rootdir id for files in sub folder uploads
# Globals: 1 variable, 1 function
# Variables - DIRIDS
# Functions - _dirname
# Arguments: 1
# ${1} = filename
# Result: read discription
###################################################
_get_rootdir_id() {
file_gen_final_list="${1:?Error: give filename}"
rootdir_gen_final_list="$(_dirname "${file_gen_final_list}")"
temp_gen_final_list="$(printf "%s\n" "${DIRIDS:?Error: DIRIDS Missing}" | grep -F "|:_//_:|${rootdir_gen_final_list}|:_//_:|" || :)"
printf "%s\n" "${temp_gen_final_list%%"|:_//_:|${rootdir_gen_final_list}|:_//_:|"}"
return 0
}
###################################################
# A extra wrapper for _upload_file function to properly handle retries
# also handle uploads in case uploading from folder
# Globals: 3 variables, 1 function
# Variables - RETRY, UPLOAD_MODE and ACCESS_TOKEN
# Functions - _upload_file
# Arguments: 3
# ${1} = parse or norparse
# ${2} = file path
# ${3} = if ${1} != parse; gdrive folder id to upload; fi
# Result: set SUCCESS var on success
###################################################
_upload_file_main() {
[ $# -lt 2 ] && printf "Missing arguments\n" && return 1
file_upload_file_main="${2}" sleep_upload_file_main=0
{ [ "${1}" = parse ] && dirid_upload_file_main="$(_get_rootdir_id "${file_upload_file_main}")"; } || dirid_upload_file_main="${3}"
retry_upload_file_main="${RETRY:-0}" && unset RETURN_STATUS
until [ "${retry_upload_file_main}" -le 0 ] && [ -n "${RETURN_STATUS}" ]; do
if [ -n "${4}" ]; then
_upload_file "${UPLOAD_MODE:-create}" "${file_upload_file_main}" "${dirid_upload_file_main}" 2>| /dev/null 1>&2 && RETURN_STATUS=1 && break
else
_upload_file "${UPLOAD_MODE:-create}" "${file_upload_file_main}" "${dirid_upload_file_main}" && RETURN_STATUS=1 && break
fi
sleep "$((sleep_upload_file_main += 1))" # on every retry, sleep the times of retry it is, e.g for 1st, sleep 1, for 2nd, sleep 2
RETURN_STATUS=2 retry_upload_file_main="$((retry_upload_file_main - 1))" && continue
done
printf "%b" "${4:+${RETURN_STATUS}\n}" 1>&"${RETURN_STATUS}"
return 0
}
###################################################
# Upload all files in the given folder, parallelly or non-parallely and show progress
# Globals: 7 variables, 3 functions
# Variables - VERBOSE, VERBOSE_PROGRESS, NO_OF_PARALLEL_JOBS, NO_OF_FILES, TMPFILE, UTILS_FOLDER and QUIET
# Functions - _clear_line, _newline, _print_center and _upload_file_main
# Arguments: 4
# ${1} = parallel or normal
# ${2} = parse or norparse
# ${3} = filenames with full path
# ${4} = if ${2} != parse; then gdrive folder id to upload; fi
# Result: read discription, set SUCCESS_STATUS & ERROR_STATUS
###################################################
_upload_folder() {
[ $# -lt 3 ] && printf "Missing arguments\n" && return 1
mode_upload_folder="${1}" PARSE_MODE="${2}" files_upload_folder="${3}" ID="${4:-}" && export PARSE_MODE ID
case "${mode_upload_folder}" in
normal)
[ "${PARSE_MODE}" = parse ] && _clear_line 1 && _newline "\n"
while read -r file <&4; do
_upload_file_main "${PARSE_MODE}" "${file}" "${ID}"
: "$((RETURN_STATUS < 2 ? (SUCCESS_STATUS += 1) : (ERROR_STATUS += 1)))"
if [ -n "${VERBOSE:-${VERBOSE_PROGRESS}}" ]; then
_print_center "justify" "Status: ${SUCCESS_STATUS} Uploaded" " | ${ERROR_STATUS} Failed" "=" && _newline "\n"
else
for _ in 1 2; do _clear_line 1; done
_print_center "justify" "Status: ${SUCCESS_STATUS} Uploaded" " | ${ERROR_STATUS} Failed" "="
fi
done 4<< EOF
$(printf "%s\n" "${files_upload_folder}")
EOF
;;
parallel)
NO_OF_PARALLEL_JOBS_FINAL="$((NO_OF_PARALLEL_JOBS > NO_OF_FILES ? NO_OF_FILES : NO_OF_PARALLEL_JOBS))"
[ -f "${TMPFILE}"SUCCESS ] && rm "${TMPFILE}"SUCCESS
[ -f "${TMPFILE}"ERROR ] && rm "${TMPFILE}"ERROR
# shellcheck disable=SC2016
(printf "%s\n" "${files_upload_folder}" | xargs -n1 -P"${NO_OF_PARALLEL_JOBS_FINAL}" -I {} sh -c '
eval "${SOURCE_UTILS}"
_upload_file_main "${PARSE_MODE}" "{}" "${ID}" true
' 1>| "${TMPFILE}"SUCCESS 2>| "${TMPFILE}"ERROR) &
pid="${!}"
until [ -f "${TMPFILE}"SUCCESS ] || [ -f "${TMPFILE}"ERORR ]; do sleep 0.5; done
[ "${PARSE_MODE}" = parse ] && _clear_line 1
_newline "\n"
until ! kill -0 "${pid}" 2>| /dev/null 1>&2; do
SUCCESS_STATUS="$(($(wc -l < "${TMPFILE}"SUCCESS)))"
ERROR_STATUS="$(($(wc -l < "${TMPFILE}"ERROR)))"
sleep 1
[ "$((SUCCESS_STATUS + ERROR_STATUS))" != "${TOTAL}" ] &&
_clear_line 1 && "${QUIET:-_print_center}" "justify" "Status" ": ${SUCCESS_STATUS} Uploaded | ${ERROR_STATUS} Failed" "="
TOTAL="$((SUCCESS_STATUS + ERROR_STATUS))"
done
SUCCESS_STATUS="$(($(wc -l < "${TMPFILE}"SUCCESS)))"
ERROR_STATUS="$(($(wc -l < "${TMPFILE}"ERROR)))"
;;
esac
return 0
}
# Upload a file to Google Drive
# shellcheck source=/dev/null
_usage() {
printf "%b" "
The script can be used to upload file/directory to google drive.\n
Usage:\n ${0##*/} [options.. ] <filename> <foldername>\n
Foldername argument is optional. If not provided, the file will be uploaded to preconfigured google drive.\n
File name argument is optional if create directory option is used.\n
Options:\n
-c | -C | --create-dir <foldername> - option to create directory. Will provide folder id. Can be used to provide input folder, see README.\n
-r | --root-dir <google_folderid> or <google_folder_url> - google folder ID/URL to which the file/directory is going to upload.
If you want to change the default value, then use this format, -r/--root-dir default=root_folder_id/root_folder_url\n
-s | --skip-subdirs - Skip creation of sub folders and upload all files inside the INPUT folder/sub-folders in the INPUT folder, use this along with -p/--parallel option to speed up the uploads.\n
-p | --parallel <no_of_files_to_parallely_upload> - Upload multiple files in parallel, Max value = 10.\n
-f | --[file|folder] - Specify files and folders explicitly in one command, use multiple times for multiple folder/files. See README for more use of this command.\n
-cl | --clone - Upload a gdrive file without downloading, require accessible gdrive link or id as argument.\n
-o | --overwrite - Overwrite the files with the same name, if present in the root folder/input folder, also works with recursive folders.\n
-d | --skip-duplicates - Do not upload the files with the same name, if already present in the root folder/input folder, also works with recursive folders.\n
-S | --share <optional_email_address>- Share the uploaded input file/folder, grant reader permission to provided email address or to everyone with the shareable link.\n
--speed 'speed' - Limit the download speed, supported formats: 1K, 1M and 1G.\n
-i | --save-info <file_to_save_info> - Save uploaded files info to the given filename.\n
-z | --config <config_path> - Override default config file with custom config file.\nIf you want to change default value, then use this format -z/--config default=default=your_config_file_path.\n
-q | --quiet - Supress the normal output, only show success/error upload messages for files, and one extra line at the beginning for folder showing no. of files and sub folders.\n
-R | --retry 'num of retries' - Retry the file upload if it fails, postive integer as argument. Currently only for file uploads.\n
-in | --include 'pattern' - Only include the files with the given pattern to upload - Applicable for folder uploads.\n
e.g: ${0##*/} local_folder --include "*1*", will only include with files with pattern '1' in the name.\n
-ex | --exclude 'pattern' - Exclude the files with the given pattern from uploading. - Applicable for folder uploads.\n
e.g: ${0##*/} local_folder --exclude "*1*", will exclude all the files pattern '1' in the name.\n
--hide - This flag will prevent the script to print sensitive information like root folder id and drivelink.\n
-v | --verbose - Display detailed message (only for non-parallel uploads).\n
-V | --verbose-progress - Display detailed message and detailed upload progress(only for non-parallel uploads).\n
--skip-internet-check - Do not check for internet connection, recommended to use in sync jobs.\n
$([ "${GUPLOAD_INSTALLED_WITH}" = script ] && printf '%s\n' '\n -u | --update - Update the installed script in your system.\n
-U | --uninstall - Uninstall script, remove related files.\n')
--info - Show detailed info, only if script is installed system wide.\n
-D | --debug - Display script command trace.\n
-h | --help - Display this message.\n"
exit 0
}
_short_help() {
printf "No valid arguments provided, use -h/--help flag to see usage.\n"
exit 0
}
###################################################
# Print the contents of info file if scipt is installed system wide.
# Path is INFO_FILE="${HOME}/.google-drive-upload/google-drive-upload.info"
# Globals: 1 variable
# INFO_FILE
# Arguments: None
# Result: read description
###################################################
_version_info() {
if command -v "${COMMAND_NAME}" 1> /dev/null && [ -n "${REPO:+${COMMAND_NAME:+${INSTALL_PATH:+${TYPE:+${TYPE_VALUE}}}}}" ]; then
for i in REPO INSTALL_PATH INSTALLATION TYPE TYPE_VALUE LATEST_INSTALLED_SHA CONFIG; do
printf "%s\n" "${i}=\"$(eval printf "%s" \"\$"${i}"\")\""
done | sed -e "s/=/: /g"
else
printf "%s\n" "google-drive-upload is not installed system wide."
fi
exit 0
}
###################################################
# Function to cleanup config file
# Remove invalid access tokens on the basis of corresponding expiry
# Globals: None
# Arguments: 1
# ${1} = config file
# Result: read description
###################################################
_cleanup_config() {
config="${1:?Error: Missing config}" && unset values_regex _tmp
! [ -f "${config}" ] && return 0
while read -r line <&4; do
expiry_value_name="${line%%=*}"
token_value_name="${expiry_value_name%%_EXPIRY}"