Skip to content

Commit

Permalink
Merge pull request #55 from Akianonymus/fix
Browse files Browse the repository at this point in the history
Update for new coding conventions | Move various functions to utils.sh | Update install.sh | Msc
  • Loading branch information
labbots authored May 21, 2020
2 parents 4cc9a9c + 8029f7c commit ae367c3
Show file tree
Hide file tree
Showing 6 changed files with 1,394 additions and 815 deletions.
27 changes: 17 additions & 10 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ For further recommendations, see [Pro Git Commit Guidelines](https://git-scm.com
- Variable names must be meaningful and self-documenting.
- Long variable names must be structured by underscores to improve legibility.
- Global variables and constants must be ALL CAPS with underscores. (eg., INPUT_FILE)
- local variables used within functions must be all lower case with underscores. (eg., post_data)
- local variables used within functions must be all lower case with underscores ( only if required ). (eg., post_data)
- Variable names can be alphanumeric with underscores. No special characters in variable names.
- Variables name must not start with number.

Expand All @@ -87,15 +87,19 @@ For further recommendations, see [Pro Git Commit Guidelines](https://git-scm.com
- Each function must contain a introductory comment. The comment must contain function name, short description of the function and description of the arguments and list of global variables used and modified.

```shell
#######################################
# Create directory in Google drive.
# Globals:
# ROOT_DIR
# Arguments:
# folder name to be created, access token.
# Returns:
# 0 if directory created successfully, non-zero on error.
#######################################
###################################################
# Create/Check directory in google drive.
# Globals: 2 variables, 3 functions
# Variables - API_URL, API_VERSION
# Functions - urlEncode, curlCmd, jsonValue
# Arguments: 3
# ${1} = dir name
# ${2} = root dir id of given dir
# ${3} = Access Token
# Result: print folder id
# Reference:
# https://developers.google.com/drive/api/v3/folder
###################################################
```
- Function names must be all lower case with underscores to seperate words (snake_case).
- Internal functions must start with underscore.
Expand All @@ -107,6 +111,9 @@ _check_connection() {
}
```

- For additing new standalone functions, use utils.sh, maintain alphabetical order.
- For using a function in install.sh, add to it directly and also utils.sh.

#### Documentation

- Refrain from making unnecessary newlines or whitespace.
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@
<p align="center">
<a href="https://github.com/labbots/google-drive-upload/stargazers"><img src="https://img.shields.io/github/stars/labbots/google-drive-upload.svg?color=blueviolet&style=for-the-badge" alt="Stars"></a>
<a href="https://github.com/labbots/google-drive-upload/releases"><img src="https://img.shields.io/github/release/labbots/google-drive-upload.svg?style=for-the-badge" alt="Latest Release"></a>
<a href="https://github.com/labbots/google-drive-upload/blob/master/LICENSE"><img src="https://img.shields.io/github/license/labbots/google-drive-upload.svg?style=for-the-badge" alt="License"></a>
<a href="https://www.codacy.com/manual/labbots/google-drive-upload?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=labbots/google-drive-upload&amp;utm_campaign=Badge_Grade"><img alt="Codacy grade" src="https://img.shields.io/codacy/grade/55b1591a28af473886c8dfdb3f2c9123?style=for-the-badge"></a>
</p>
<p align="center">
<a href="https://github.com/labbots/google-drive-upload/blob/master/LICENSE"><img src="https://img.shields.io/github/license/labbots/google-drive-upload.svg?style=for-the-badge" alt="License"></a>
<a href="https://plant.treeware.earth/labbots/google-drive-upload"><img alt="Buy us a tree" src="https://img.shields.io/treeware/trees/labbots/google-drive-upload?color=green&label=Buy%20us%20a%20Tree%20%F0%9F%8C%B3&style=for-the-badge"></a>
</p>

Expand Down
91 changes: 33 additions & 58 deletions google-oauth2.sh
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
# Set CLIENT_ID and CLIENT_SECRET and SCOPE
# See SCOPES at https://developers.google.com/identity/protocols/oauth2/scopes#docsv1

shortHelp() {
_short_help() {
printf "
No valid arguments provided.
Usage:
Expand All @@ -22,51 +22,26 @@ Usage:
exit 0
}

[[ ${1} = create ]] || [[ ${1} = refresh ]] || shortHelp
[[ ${1} = create ]] || [[ ${1} = refresh ]] || _short_help

[[ ${2} = update ]] && UPDATE="updateConfig"
[[ ${2} = update ]] && UPDATE="_update_config"

# Move cursor to nth no. of line and clear it to the begining.
clearLine() {
printf "\033[%sA\033[2K" "${1}"
}

# Method to extract data from json response.
# Usage: jsonValue key < json ( or use with a pipe output ).
jsonValue() {
[[ $# = 0 ]] && printf "%s: Missing arguments\n" "${FUNCNAME[0]}" && return 1
declare LC_ALL=C num="${2:-1}"
grep -o "\"""${1}""\"\:.*" | sed -e "s/.*\"""${1}""\": //" -e 's/[",]*$//' -e 's/["]*$//' -e 's/[,]*$//' -e "s/\"//" -n -e "${num}"p
}

# Remove array duplicates, maintain the order as original.
# Usage: removeArrayDuplicates "${somearray[@]}"
# https://stackoverflow.com/a/37962595
removeArrayDuplicates() {
[[ $# = 0 ]] && printf "%s: Missing arguments\n" "${FUNCNAME[0]}" && return 1
declare -A Aseen
Aunique=()
for i in "$@"; do
{ [[ -z ${i} || ${Aseen[${i}]} ]]; } && continue
Aunique+=("${i}") && Aseen[${i}]=x
done
printf '%s\n' "${Aunique[@]}"
}
UTILS_FILE="${UTILS_FILE:-./utils.sh}"
if [[ -r ${UTILS_FILE} ]]; then
# shellcheck source=/dev/null
source "${UTILS_FILE}" || { printf "Error: Unable to source utils file ( %s ) .\n" "${UTILS_FILE}" && exit 1; }
else
printf "Error: Utils file ( %s ) not found\n" "${UTILS_FILE}"
exit 1
fi

# Update Config. Incase of old value, update, for new value add.
# Usage: updateConfig valuename value configpath
updateConfig() {
[[ $# -lt 3 ]] && printf "%s: Missing arguments\n" "${FUNCNAME[0]}" && return 1
declare VALUE_NAME="${1}" VALUE="${2}" CONFIG_PATH="${3}" FINAL=()
printf "" >> "${CONFIG_PATH}" # If config file doesn't exist.
mapfile -t VALUES < "${CONFIG_PATH}" && VALUES+=("${VALUE_NAME}=\"${VALUE}\"")
for i in "${VALUES[@]}"; do
[[ ${i} =~ ${VALUE_NAME}\= ]] && FINAL+=("${VALUE_NAME}=\"${VALUE}\"") || FINAL+=("${i}")
done
removeArrayDuplicates "${FINAL[@]}" >| "${CONFIG_PATH}"
}
if ! _is_terminal; then
DEBUG="true"
export DEBUG
fi
_check_debug

printf "Starting script..\n"
_print_center "justify" "Starting script.." "-"

CLIENT_ID=""
CLIENT_SECRET=""
Expand All @@ -77,24 +52,24 @@ TOKEN_URL="https://accounts.google.com/o/oauth2/token"
# shellcheck source=/dev/null
[[ -f ${HOME}/.googledrive.conf ]] && source "${HOME}"/.googledrive.conf

printf "Checking credentials..\n"
_print_center "justify" "Checking credentials.." "-"

# Credentials
if [[ -z ${CLIENT_ID} ]]; then
read -r -p "Client ID: " CLIENT_ID
[[ -z ${CLIENT_ID} ]] && printf "Error: No value provided.\n" 1>&2 && exit 1
updateConfig CLIENT_ID "${CLIENT_ID}" "${HOME}"/.googledrive.conf
_update_config CLIENT_ID "${CLIENT_ID}" "${HOME}"/.googledrive.conf
fi
if [[ -z ${CLIENT_SECRET} ]]; then
read -r -p "Client Secret: " CLIENT_SECRET
[[ -z ${CLIENT_SECRET} ]] && printf "Error: No value provided.\n" 1>&2 && exit 1
updateConfig CLIENT_SECRET "${CLIENT_SECRET}" "${HOME}"/.googledrive.conf
_update_config CLIENT_SECRET "${CLIENT_SECRET}" "${HOME}"/.googledrive.conf
fi

for _ in {1..2}; do clearLine 1; done
for _ in {1..2}; do _clear_line 1; done

if [[ ${1} = create ]]; then
printf "Required credentials set.\n"
_print_center "justify" "Required credentials set." "="
printf "Visit the below URL, tap on allow and then enter the code obtained:\n"
URL="https://accounts.google.com/o/oauth2/auth?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&scope=${SCOPE}&response_type=code&prompt=consent"
printf "%s\n\n" "${URL}"
Expand All @@ -104,8 +79,8 @@ if [[ ${1} = create ]]; then
if [[ -n ${CODE} ]]; then
RESPONSE="$(curl --compressed -s -X POST --data "client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&refresh_token=${REFRESH_TOKEN}&grant_type=refresh_token" ${TOKEN_URL})"

ACCESS_TOKEN="$(jsonValue access_token <<< "${RESPONSE}")"
REFRESH_TOKEN="$(jsonValue refresh_token <<< "${RESPONSE}")"
ACCESS_TOKEN="$(_json_value access_token <<< "${RESPONSE}")"
REFRESH_TOKEN="$(_json_value refresh_token <<< "${RESPONSE}")"

if [[ -n ${ACCESS_TOKEN} && -n ${REFRESH_TOKEN} ]]; then
"${UPDATE:-:}" REFRESH_TOKEN "${REFRESH_TOKEN}" "${CONFIG:-${HOME}/.googledrive.conf}"
Expand All @@ -114,28 +89,28 @@ if [[ ${1} = create ]]; then
printf "Access Token: %s\n" "${ACCESS_TOKEN}"
printf "Refresh Token: %s\n" "${REFRESH_TOKEN}"
else
printf "Error: Wrong code given, make sure you copy the exact code\n"
_print_center "normal" "Error: Wrong code given, make sure you copy the exact code." "="
exit 1
fi
else
printf "\nNo code provided, run the script and try again.\n"
_print_center "justify" "No code provided, run the script and try again." "="
exit 1
fi
elif [[ ${1} = refresh ]]; then
# Method to regenerate access_token ( also updates in config ).
# 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.
# Requirements: Refresh Token
getTokenandUpdate() {
_get_token_and__update() {
RESPONSE="$(curl --compressed -s -X POST --data "client_id=${CLIENT_ID}&client_secret=${CLIENT_SECRET}&refresh_token=${REFRESH_TOKEN}&grant_type=refresh_token" "${TOKEN_URL}")"
ACCESS_TOKEN="$(jsonValue access_token <<< "${RESPONSE}")"
ACCESS_TOKEN="$(_json_value access_token <<< "${RESPONSE}")"
"${UPDATE:-:}" ACCESS_TOKEN "${ACCESS_TOKEN}" "${CONFIG:-${HOME}/.googledrive.conf}"
}
if [[ -n ${REFRESH_TOKEN} ]]; then
printf "Required credentials set.\n"
getTokenandUpdate
clearLine 1
_print_center "justify" "Required credentials set." "="
_get_token_and__update
_clear_line 1
printf "Access Token: %s\n" "${ACCESS_TOKEN}"
else
printf "Refresh Token not set, use %s create to generate one.\n" "${0}"
_print_center "normal" "Refresh Token not set, use ${0} create to generate one." "="
fi
fi
Loading

0 comments on commit ae367c3

Please sign in to comment.