-
Notifications
You must be signed in to change notification settings - Fork 144
/
gupload
executable file
·2196 lines (2013 loc) · 109 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() {
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." "="
return 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}"
}
###################################################
# Encode the given string to parse properly as json
# Globals: None
# Arguments: 1
# ${1} = string
# Result: print encoded string
# Reference:
# https://tools.ietf.org/html/rfc7159#section-7
###################################################
_json_escape() {
input_json_escape="${1:?Provide Input}" output_json_escape=""
output_json_escape="$(printf "%s" "${input_json_escape}" | sed \
-e "s|'\'|'\\'|g" \
-e "s|'/'|'\/'|g" \
-e "s|'|\'|g" \
-e 's/\"/\\\"/g' \
-e ':a; $!N' \
-e 's|\t|\\t|g' \
-e 's|\r|\\r|g' \
-e 's|\f|\\f|g' | awk -v ORS='\\n' '1')"
# use awk because sed just messes up with newlines
printf "%s" "${output_json_escape}"
}
###################################################
# 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
}
###################################################
# Quiet version of _print_center
###################################################
_print_center_quiet() {
{ [ $# = 3 ] && printf "%s\n" "${2}"; } || printf "%s%s\n" "${2}" "${3}"
}
###################################################
# Evaluates value1=value2
# Globals: None
# Arguments: 3
# ${1} = direct ( d ) or indirect ( i ) - ( evaluation mode )
# ${2} = var name
# ${3} = var value
# Result: export value1=value2
###################################################
_set_value() {
mode_set_value="${1:?}" var_set_value="${2:?}" value_set_value="${3:?}"
case "${mode_set_value}" in
d | direct) export "${var_set_value}=${value_set_value}" ;;
i | indirect) export "${var_set_value}=$(eval printf "%s" \"\$"${value_set_value}"\")" ;;
esac
}
###################################################
# 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}" || return 1
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}" || return 1
chmod a-w-r-x,u+r "${config_path_update_config}" || return 1
return 0
}
###################################################
# 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}"
)
# auth utils for Google Drive
# shellcheck source=/dev/null
###################################################
# Check if account name is valid by a regex expression
# Globals: None
# Arguments: 1
# ${1} = Account name
# Result: read description and return 1 or 0
###################################################
_account_name_valid() {
name_account_name_valid="${1:?}" account_name_regex_account_name_valid='^([A-Za-z0-9_])+$'
printf "%s\n" "${name_account_name_valid}" | grep -qE "${account_name_regex_account_name_valid}" || return 1
return 0
}
###################################################
# Check if account exists
# First check if the given account is in correct format
# Globals: 2 functions
# _set_value, _account_name_valid
# Arguments: 1
# ${1} = Account name
# Result: read description and return 1 or 0
###################################################
_account_exists() {
name_account_exists="${1:-}" client_id_account_exists="" client_secret_account_exists="" refresh_token_account_exists=""
_account_name_valid "${name_account_exists}" || return 1
_set_value indirect client_id_account_exists "ACCOUNT_${name_account_exists}_CLIENT_ID"
_set_value indirect client_secret_account_exists "ACCOUNT_${name_account_exists}_CLIENT_SECRET"
_set_value indirect refresh_token_account_exists "ACCOUNT_${name_account_exists}_REFRESH_TOKEN"
[ -z "${client_id_account_exists:+${client_secret_account_exists:+${refresh_token_account_exists}}}" ] && return 1
return 0
}
###################################################
# Show all accounts configured in config file
# Globals: 2 variables, 4 functions
# Variable - CONFIG, QUIET
# Functions - _account_exists, _set_value, _print_center, _reload_config
# Arguments: None
# Result: SHOW all accounts, export COUNT and ACC_${count}_ACC dynamic variables
# or print "No accounts configured yet."
###################################################
_all_accounts() {
{ _reload_config && _handle_old_config; } || return 1
COUNT=0
while read -r account <&4 && [ -n "${account}" ]; do
_account_exists "${account}" &&
{ [ "${COUNT}" = 0 ] && "${QUIET:-_print_center}" "normal" " All available accounts. " "=" || :; } &&
printf "%b" "$((COUNT += 1)). ${account} \n" && _set_value direct "ACC_${COUNT}_ACC" "${account}"
done 4<< EOF
$(grep -oE '^ACCOUNT_.*_CLIENT_ID' "${CONFIG}" | sed -e "s/ACCOUNT_//g" -e "s/_CLIENT_ID//g")
EOF
{ [ "${COUNT}" -le 0 ] && "${QUIET:-_print_center}" "normal" " No accounts configured yet. " "=" 1>&2; } || printf '\n'
return 0
}
###################################################
# Setup a new account name
# If given account name is configured already, then ask for name
# after name has been properly setup, export ACCOUNT_NAME var
# Globals: 1 variable, 5 functions
# Variable - QUIET
# Functions - _print_center, _account_exists, _clear_line, _account_name_valid, _reload_config
# Arguments: 1
# ${1} = Account name ( optional )
# Result: read description and export ACCOUNT_NAME NEW_ACCOUNT_NAME
###################################################
_set_new_account_name() {
_reload_config || return 1
new_account_name_set_new_account_name="${1:-}" && unset name_valid_set_new_account_name
[ -z "${new_account_name_set_new_account_name}" ] && {
_all_accounts 2>| /dev/null
"${QUIET:-_print_center}" "normal" " New account name: " "="
"${QUIET:-_print_center}" "normal" "Info: Account names can only contain alphabets / numbers / dashes." " " && printf '\n'
}
until [ -n "${name_valid_set_new_account_name}" ]; do
if [ -n "${new_account_name_set_new_account_name}" ]; then
if _account_name_valid "${new_account_name_set_new_account_name}"; then
if _account_exists "${new_account_name_set_new_account_name}"; then
"${QUIET:-_print_center}" "normal" " Warning: Given account ( ${new_account_name_set_new_account_name} ) already exists, input different name. " "-" 1>&2
unset new_account_name_set_new_account_name && continue
else
export new_account_name_set_new_account_name="${new_account_name_set_new_account_name}" ACCOUNT_NAME="${new_account_name_set_new_account_name}" &&
name_valid_set_new_account_name="true" && continue
fi
else
"${QUIET:-_print_center}" "normal" " Warning: Given account name ( ${new_account_name_set_new_account_name} ) invalid, input different name. " "-"
unset new_account_name_set_new_account_name && continue
fi
else
[ -t 1 ] || { "${QUIET:-_print_center}" "normal" " Error: Not running in an interactive terminal, cannot ask for new account name. " 1>&2 && return 1; }
printf -- "-> \e[?7l"
read -r new_account_name_set_new_account_name
printf '\e[?7h'
fi
_clear_line 1
done
"${QUIET:-_print_center}" "normal" " Given account name: ${NEW_ACCOUNT_NAME} " "="
export ACCOUNT_NAME="${NEW_ACCOUNT_NAME}"
return 0
}
###################################################
# Delete a account from config file
# Globals: 2 variables, 3 functions
# Variables - CONFIG, QUIET
# Functions - _account_exists, _print_center, _reload_config
# Arguments: None
# Result: check if account exists and delete from config, else print error message
###################################################
_delete_account() {
{ _reload_config && _handle_old_config; } || return 1
account_delete_account="${1:?Error: give account name}" && unset regex_delete_account config_without_values_delete_account
if _account_exists "${account_delete_account}"; then
regex_delete_account="^ACCOUNT_${account_delete_account}_(CLIENT_ID=|CLIENT_SECRET=|REFRESH_TOKEN=|ROOT_FOLDER=|ROOT_FOLDER_NAME=|ACCESS_TOKEN=|ACCESS_TOKEN_EXPIRY=)|DEFAULT_ACCOUNT=\"${account_delete_account}\""
config_without_values_delete_account="$(grep -vE "${regex_delete_account}" "${CONFIG}")"
chmod u+w "${CONFIG}" || return 1 # change perms to edit
printf "%s\n" "${config_without_values_delete_account}" >| "${CONFIG}" || return 1
chmod "a-w-r-x,u+r" "${CONFIG}" || return 1 # restore perms
"${QUIET:-_print_center}" "normal" " Successfully deleted account ( ${account_delete_account} ) from config. " "-"
else
"${QUIET:-_print_center}" "normal" " Error: Cannot delete account ( ${account_delete_account} ) from config. No such account exists " "-" 1>&2
fi
return 0
}
###################################################
# handle legacy config
# this will be triggered only if old config values are present, convert to new format
# new account will be created with "default" name, if default already taken, then add a number as suffix
# Globals: 7 variables, 2 functions
# Variables - CLIENT_ID CLIENT_SECRET, REFRESH_TOKEN, ROOT_FOLDER, ROOT_FOLDER_NAME CONFIG, ACCOUNT_NAME
# Functions - _account_exists, _reload_config
# Arguments: None
###################################################
_handle_old_config() {
export CLIENT_ID CLIENT_SECRET REFRESH_TOKEN # to handle a shellcheck warning
# only try to convert the if all three values are present
[ -n "${CLIENT_ID:+${CLIENT_SECRET:+${REFRESH_TOKEN}}}" ] && {
account_name_handle_old_config="default" regex_check_handle_old_config config_without_values_handle_old_config count_handle_old_config
# first try to name the new account as default, otherwise try to add numbers as suffix
until ! _account_exists "${account_name_handle_old_config}"; do
account_name_handle_old_config="${account_name_handle_old_config}$((count_handle_old_config += 1))"
done
regex_check_handle_old_config="^(CLIENT_ID=|CLIENT_SECRET=|REFRESH_TOKEN=|ROOT_FOLDER=|ROOT_FOLDER_NAME=|ACCESS_TOKEN=|ACCESS_TOKEN_EXPIRY=)"
config_without_values_handle_old_config="$(grep -vE "${regex_check_handle_old_config}" "${CONFIG}")"
chmod u+w "${CONFIG}" || return 1 # change perms to edit
printf "%s\n%s\n%s\n%s\n%s\n%s\n" \
"ACCOUNT_${account_name_handle_old_config}_CLIENT_ID=\"${CLIENT_ID}\"" \
"ACCOUNT_${account_name_handle_old_config}_CLIENT_SECRET=\"${CLIENT_SECRET}\"" \
"ACCOUNT_${account_name_handle_old_config}_REFRESH_TOKEN=\"${REFRESH_TOKEN}\"" \
"ACCOUNT_${account_name_handle_old_config}_ROOT_FOLDER=\"${ROOT_FOLDER}\"" \
"ACCOUNT_${account_name_handle_old_config}_ROOT_FOLDER_NAME=\"${ROOT_FOLDER_NAME}\"" \
"${config_without_values_handle_old_config}" >| "${CONFIG}" || return 1
chmod "a-w-r-x,u+r" "${CONFIG}" || return 1 # restore perms
_reload_config || return 1 # reload config file
}
return 0
}
###################################################
# handle old config values, new account creation, custom account name, updating default config and account
# start token service if applicable
# Globals: 12 variables, 7 functions
# Variables - DEFAULT_CONFIG, NEW_ACCOUNT_NAME, CUSTOM_ACCOUNT_NAME, DELETE_ACCOUNT_NAME, LIST_ACCOUNTS, QUIET
# UPDATE_DEFAULT_ACCOUNT, UPDATE_DEFAULT_CONFIG, CONFIG_INFO, CONTINUE_WITH_NO_INPUT
# Functions - _reload_config, _handle_old_config, _set_new_account_name, _account_exists, _all_accounts
# _check_account_credentials, _token_bg_service, _print_center, _update_config, _set_value
# Arguments: None
# Result: read description and start access token check in bg if required
###################################################
_check_credentials() {
{ _reload_config && _handle_old_config; } || return 1
# set account name to default account name
ACCOUNT_NAME="${DEFAULT_ACCOUNT}"
# if old values exist in config
if [ -n "${NEW_ACCOUNT_NAME}" ]; then
# create new account, --create-account flag
_set_new_account_name "${NEW_ACCOUNT_NAME}" || return 1
_check_account_credentials "${ACCOUNT_NAME}" || return 1
else
if [ -n "${CUSTOM_ACCOUNT_NAME}" ]; then
if _account_exists "${CUSTOM_ACCOUNT_NAME}"; then
ACCOUNT_NAME="${CUSTOM_ACCOUNT_NAME}"
else
# error out in case CUSTOM_ACCOUNT_NAME is invalid
"${QUIET:-_print_center}" "normal" " Error: No such account ( ${CUSTOM_ACCOUNT_NAME} ) exists. " "-" && return 1
fi
elif [ -n "${DEFAULT_ACCOUNT}" ]; then
# check if default account if valid or not, else set account name to nothing and remove default account in config
_account_exists "${DEFAULT_ACCOUNT}" || {
_update_config DEFAULT_ACCOUNT "" "${CONFIG}" && unset DEFAULT_ACCOUNT ACCOUNT_NAME && UPDATE_DEFAULT_ACCOUNT="_update_config"
}
# UPDATE_DEFAULT_ACCOUNT to true so that default config is updated later
else
UPDATE_DEFAULT_ACCOUNT="_update_config" # as default account doesn't exist
fi
# in case no account name was set
if [ -z "${ACCOUNT_NAME}" ]; then
# if accounts are configured but default account is not set
if _all_accounts 2>| /dev/null && [ "${COUNT}" -gt 0 ]; then
# when only 1 account is configured, then set it as default
if [ "${COUNT}" -eq 1 ]; then
_set_value indirect ACCOUNT_NAME "ACC_1_ACC" # ACC_1_ACC comes from _all_accounts function
else
"${QUIET:-_print_center}" "normal" " Above accounts are configured, but default one not set. " "="
if [ -t 1 ]; then
"${QUIET:-_print_center}" "normal" " Choose default account: " "-"
until [ -n "${ACCOUNT_NAME}" ]; do
printf -- "-> \e[?7l"
read -r account_name_check_credentials
printf '\e[?7h'
if [ "${account_name_check_credentials}" -gt 0 ] && [ "${account_name_check_credentials}" -le "${COUNT}" ]; then
_set_value indirect ACCOUNT_NAME "ACC_${COUNT}_ACC"
else
_clear_line 1
fi
done
else
# if not running in a terminal then choose 1st one as default
printf "%s\n" "Warning: Script is not running in a terminal, choosing first account as default."
_set_value indirect ACCOUNT_NAME "ACC_1_ACC" # ACC_1_ACC comes from _all_accounts function
fi
fi
else
_set_new_account_name "" || return 1
_check_account_credentials "${ACCOUNT_NAME}" || return 1
fi
fi
_check_account_credentials "${ACCOUNT_NAME}" || return 1
fi
"${UPDATE_DEFAULT_ACCOUNT:-:}" DEFAULT_ACCOUNT "${ACCOUNT_NAME}" "${CONFIG}" # update default account if required
"${UPDATE_DEFAULT_CONFIG:-:}" CONFIG "${CONFIG}" "${CONFIG_INFO}" # update default config if required
[ -n "${CONTINUE_WITH_NO_INPUT}" ] || _token_bg_service # launch token bg service
return 0
}
###################################################
# check credentials for a given account name
# Globals: 3 functions
# Functions - _check_client, _check_refresh_token, _check_access_token
# Arguments: 2
# ${1} = Account name
# Result: read description, return 1 or 0
###################################################
_check_account_credentials() {
account_name_check_account_credentials="${1:?Give account name}"
{
_check_client ID "${account_name_check_account_credentials}" &&
_check_client SECRET "${account_name_check_account_credentials}" &&
_check_refresh_token "${account_name_check_account_credentials}" &&
_check_access_token "${account_name_check_account_credentials}" check
} || return 1
return 0
}
###################################################
# Check client id or secret and ask if required
# Globals: 4 variables, 3 functions
# Variables - CONFIG, QUIET, CLIENT_ID_${ACCOUNT_NAME}, CLIENT_SECRET_${ACCOUNT_NAME}
# Functions - _print_center, _update_config, _set_value
# Arguments: 2
# ${1} = ID or SECRET
# ${2} = Account name ( optional - if not given, then just CLIENT_[ID|SECRET] var is used )
# Result: read description and export ACCOUNT_name_CLIENT_[ID|SECRET] CLIENT_[ID|SECRET]
###################################################
_check_client() {
type_check_client="CLIENT_${1:?Error: ID or SECRET}" account_name_check_client="${2:-}"
type_value_check_client="" type_regex_check_client="" &&
unset type_name_check_client valid_check_client client_check_client message_check_client
export client_id_regex='[0-9]+-[0-9A-Za-z_]{32}\.apps\.googleusercontent\.com' client_secret_regex='[0-9A-Za-z_-]+'
type_name_check_client="${account_name_check_client:+ACCOUNT_${account_name_check_client}_}${type_check_client}"
# set the type_value to the actual value of ACCOUNT_${account_name}_[ID|SECRET]
_set_value indirect type_value_check_client "${type_name_check_client}"
# set the type_regex to the actual value of client_id_regex or client_secret_regex
_set_value indirect type_regex_check_client "${type_check_client}_regex"
until [ -n "${type_value_check_client}" ] && [ -n "${valid_check_client}" ]; do
[ -n "${type_value_check_client}" ] && {
if printf "%s\n" "${type_value_check_client}" | grep -qE "${type_regex_check_client}"; then
[ -n "${client_check_client}" ] && { _update_config "${type_name_check_client}" "${type_value_check_client}" "${CONFIG}" || return 1; }
valid_check_client="true" && continue
else
{ [ -n "${client_check_client}" ] && message_check_client="- Try again"; } || message_check_client="in config ( ${CONFIG} )"
"${QUIET:-_print_center}" "normal" " Invalid Client ${1} ${message_check_client} " "-" && unset "${type_name_check_client}" client
fi
}
[ -z "${client_check_client}" ] && printf "\n" && "${QUIET:-_print_center}" "normal" " Enter Client ${1} " "-"
[ -n "${client_check_client}" ] && _clear_line 1
printf -- "-> "
read -r "${type_name_check_client?}" && client_check_client=1
_set_value indirect type_value_check_client "${type_name_check_client}"
done
# export ACCOUNT_name_CLIENT_[ID|SECRET]
_set_value direct "${type_name_check_client}" "${type_value_check_client}"
# export CLIENT_[ID|SECRET]
_set_value direct "${type_check_client}" "${type_value_check_client}"
return 0
}
###################################################
# Check refresh token and ask if required
# Globals: 8 variables, 4 functions
# Variables - CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, TOKEN_URL, CONFIG, QUIET
# Functions - _set_value, _print_center, _update_config, _check_access_token
# Arguments: 1
# ${1} = Account name ( optional - if not given, then just REFRESH_TOKEN var is used )
# Result: read description & export REFRESH_TOKEN ACCOUNT_${account_name}_REFRESH_TOKEN
###################################################
_check_refresh_token() {
# bail out before doing anything if client id and secret is not present, unlikely to happen but just in case
[ -z "${CLIENT_ID:+${CLIENT_SECRET}}" ] && return 1
account_name_check_refresh_token="${1:-}"
refresh_token_regex='[0-9]//[0-9A-Za-z_-]+' authorization_code_regex='[0-9]/[0-9A-Za-z_-]+'
refresh_token_name_check_refresh_token="${account_name_check_refresh_token:+ACCOUNT_${account_name_check_refresh_token}_}REFRESH_TOKEN"
_set_value indirect refresh_token_value_check_refresh_token "${refresh_token_name_check_refresh_token}"
[ -n "${refresh_token_value_check_refresh_token}" ] && {
! printf "%s\n" "${refresh_token_value_check_refresh_token}" | grep -qE "${refresh_token_regex}" &&
"${QUIET:-_print_center}" "normal" " Error: Invalid Refresh token in config file, follow below steps.. " "-" && unset refresh_token_value_check_refresh_token
}
[ -z "${refresh_token_value_check_refresh_token}" ] && {
printf "\n" && "${QUIET:-_print_center}" "normal" "If you have a refresh token generated, then type the token, else leave blank and press return key.." " "
printf "\n" && "${QUIET:-_print_center}" "normal" " Refresh Token " "-" && printf -- "-> "
read -r refresh_token_value_check_refresh_token
if [ -n "${refresh_token_value_check_refresh_token}" ]; then
"${QUIET:-_print_center}" "normal" " Checking refresh token.. " "-"
if printf "%s\n" "${refresh_token_value_check_refresh_token}" | grep -qE "${refresh_token_regex}"; then
_set_value direct REFRESH_TOKEN "${refresh_token_value_check_refresh_token}"
{ _check_access_token "${account_name_check_refresh_token}" skip_check &&
_update_config "${refresh_token_name_check_refresh_token}" "${refresh_token_value_check_refresh_token}" "${CONFIG}" &&
_clear_line 1; } || check_error_check_refresh_token=true
else
check_error_check_refresh_token=true
fi
[ -n "${check_error_check_refresh_token}" ] && "${QUIET:-_print_center}" "normal" " Error: Invalid Refresh token given, follow below steps to generate.. " "-" && unset refresh_token_value_check_refresh_token
else
"${QUIET:-_print_center}" "normal" " No Refresh token given, follow below steps to generate.. " "-" && unset refresh_token_value_check_refresh_token
fi
[ -z "${refresh_token_value_check_refresh_token}" ] && {
printf "\n" && "${QUIET:-_print_center}" "normal" "Visit the below URL, tap on allow and then enter the code obtained" " "
URL="https://accounts.google.com/o/oauth2/auth?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&scope=${SCOPE}&response_type=code&prompt=consent"
printf "\n%s\n" "${URL}"
unset AUTHORIZATION_CODE authorization_code AUTHORIZATION_CODE_VALID response
until [ -n "${AUTHORIZATION_CODE}" ] && [ -n "${AUTHORIZATION_CODE_VALID}" ]; do
[ -n "${AUTHORIZATION_CODE}" ] && {
if printf "%s\n" "${AUTHORIZATION_CODE}" | grep -qE "${authorization_code_regex}"; then
AUTHORIZATION_CODE_VALID="true" && continue
else
"${QUIET:-_print_center}" "normal" " Invalid CODE given, try again.. " "-" && unset AUTHORIZATION_CODE authorization_code
fi
}
{ [ -z "${authorization_code}" ] && printf "\n" && "${QUIET:-_print_center}" "normal" " Enter the authorization code " "-"; } || _clear_line 1
printf -- "-> \e[?7l"
read -r AUTHORIZATION_CODE && authorization_code=1
printf '\e[?7h'
done
response_check_refresh_token="$(curl --compressed "${CURL_PROGRESS}" -X POST \
--data "code=${AUTHORIZATION_CODE}&client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&redirect_uri=${REDIRECT_URI}&grant_type=authorization_code" "${TOKEN_URL}")" || :
_clear_line 1 1>&2
refresh_token_value_check_refresh_token="$(printf "%s\n" "${response_check_refresh_token}" | _json_value refresh_token 1 1)" ||
{ printf "%s\n" "Error: Cannot fetch refresh token, make sure the authorization code was correct." && return 1; }
_set_value direct REFRESH_TOKEN "${refresh_token_value_check_refresh_token}"
{ _check_access_token "${account_name_check_refresh_token}" skip_check "${response_check_refresh_token}" &&
_update_config "${refresh_token_name_check_refresh_token}" "${refresh_token_value_check_refresh_token}" "${CONFIG}"; } || return 1
}
printf "\n"
}
# export account_name_check_refresh_token_REFRESH_TOKEN
_set_value direct "${refresh_token_name_check_refresh_token}" "${refresh_token_value_check_refresh_token}"
# export REFRESH_TOKEN
_set_value direct REFRESH_TOKEN "${refresh_token_value_check_refresh_token}"
return 0
}
###################################################
# Check access token and create/update if required
# Also update in config
# Globals: 9 variables, 3 functions
# Variables - CLIENT_ID, CLIENT_SECRET, REFRESH_TOKEN, TOKEN_URL, CONFIG, API_URL, API_VERSION, QUIET
# Functions - _print_center, _update_config, _set_value
# Arguments: 2
# ${1} = Account name ( if not given, then just ACCESS_TOKEN var is used )
# ${2} = if skip_check, then force create access token, else check with regex and expiry
# ${3} = json response ( optional )
# Result: read description & export ACCESS_TOKEN ACCESS_TOKEN_EXPIRY
###################################################
_check_access_token() {
# bail out before doing anything if client id|secret or refresh token is not present, unlikely to happen but just in case
[ -z "${CLIENT_ID:+${CLIENT_SECRET:+${REFRESH_TOKEN}}}" ] && return 1
account_name_check_access_token="${1:-}" no_check_check_access_token="${2:-false}" response_json_check_access_token="${3:-}"
unset token_name_check_access_token token_expiry_name_check_access_token token_value_check_access_token token_expiry_value_check_access_token response_check_access_token
access_token_regex='ya29\.[0-9A-Za-z_-]+'
token_name_check_access_token="${account_name_check_access_token:+ACCOUNT_${account_name_check_access_token}_}ACCESS_TOKEN"
token_expiry_name_check_access_token="${token_name_check_access_token}_EXPIRY"
_set_value indirect token_value_check_access_token "${token_name_check_access_token}"
_set_value indirect token_expiry_value_check_access_token "${token_expiry_name_check_access_token}"
[ "${no_check_check_access_token}" = skip_check ] || [ -z "${token_value_check_access_token}" ] || [ "${token_expiry_value_check_access_token:-0}" -lt "$(date +"%s")" ] || ! printf "%s\n" "${token_value_check_access_token}" | grep -qE "${access_token_regex}" && {
response_check_access_token="${response_json_check_access_token:-$(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 token_value_check_access_token="$(printf "%s\n" "${response_check_access_token}" | _json_value access_token 1 1)"; then
token_expiry_value_check_access_token="$(($(date +"%s") + $(printf "%s\n" "${response_check_access_token}" | _json_value expires_in 1 1) - 1))"
_update_config "${token_name_check_access_token}" "${token_value_check_access_token}" "${CONFIG}" || return 1
_update_config "${token_expiry_name_check_access_token}" "${token_expiry_value_check_access_token}" "${CONFIG}" || return 1
else
"${QUIET:-_print_center}" "justify" "Error: Something went wrong" ", printing error." "=" 1>&2
printf "%s\n" "${response_check_access_token}" 1>&2
return 1
fi
}
# export ACCESS_TOKEN and ACCESS_TOKEN_EXPIRY
_set_value direct ACCESS_TOKEN "${token_value_check_access_token}"
_set_value direct ACCESS_TOKEN_EXPIRY "${token_expiry_value_check_access_token}"
# export INITIAL_ACCESS_TOKEN which is used on script cleanup
_set_value direct INITIAL_ACCESS_TOKEN "${ACCESS_TOKEN}"
return 0
}
###################################################
# load config file if available, else create a empty file
# uses global variable CONFIG
###################################################
_reload_config() {
{ [ -r "${CONFIG}" ] && . "${CONFIG}"; } || { printf "" >> "${CONFIG}" || return 1; }
return 0
}
###################################################
# launch a background service to check access token and update it
# checks ACCESS_TOKEN_EXPIRY, try to update before 5 mins of expiry, a fresh token gets 60 mins
# process will be killed when script exits or "${MAIN_PID}" is killed
# Globals: 4 variables, 1 function
# Variables - ACCESS_TOKEN, ACCESS_TOKEN_EXPIRY, MAIN_PID, TMPFILE
# Functions - _check_access_token
# Arguments: None
# Result: read description & export ACCESS_TOKEN_SERVICE_PID
###################################################
_token_bg_service() {
[ -z "${MAIN_PID}" ] && return 0 # don't start if MAIN_PID is empty
printf "%b\n" "ACCESS_TOKEN=\"${ACCESS_TOKEN}\"\nACCESS_TOKEN_EXPIRY=\"${ACCESS_TOKEN_EXPIRY}\"" >| "${TMPFILE}_ACCESS_TOKEN"
{
until ! kill -0 "${MAIN_PID}" 2>| /dev/null 1>&2; do
. "${TMPFILE}_ACCESS_TOKEN"
CURRENT_TIME="$(date +"%s")"
REMAINING_TOKEN_TIME="$((ACCESS_TOKEN_EXPIRY - CURRENT_TIME))"
if [ "${REMAINING_TOKEN_TIME}" -le 300 ]; then
# timeout after 30 seconds, it shouldn't take too long anyway, and update tmp config
CONFIG="${TMPFILE}_ACCESS_TOKEN" _timeout 30 _check_access_token "" skip_check || :
else
TOKEN_PROCESS_TIME_TO_SLEEP="$(if [ "${REMAINING_TOKEN_TIME}" -le 301 ]; then
printf "0\n"
else
printf "%s\n" "$((REMAINING_TOKEN_TIME - 300))"
fi)"
sleep "${TOKEN_PROCESS_TIME_TO_SLEEP}"
fi
sleep 1
done
} &
export ACCESS_TOKEN_SERVICE_PID="${!}"
return 0
}
###################################################
# 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, DESCRIPTION_FILE
# 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 description_clone_file && STRING="Cloned"
readable_size_clone_file="$(printf "%s\n" "${size_clone_file}" | _bytes_to_human)"
# create description data
[ -n "${DESCRIPTION_FILE}" ] && {
description_clone_file="$(printf "%s\n" "${DESCRIPTION_FILE}" | sed -e "s|%f|${name_clone_file}|g|" -e "s|%f|${readable_size_clone_file}|g|")"
description_clone_file="$(_json_escape "${description_clone_file}")" # escape for json
}
post_data_clone_file="{\"parents\": [\"${file_root_id_clone_file}\"]${description_clone_file:+,\"description\":\"${description_clone_file}\"}}"
_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}}" || return 1; }
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