Created
October 13, 2024 18:11
-
-
Save tsjk/35390851d5e935507c2d9c68ec782714 to your computer and use it in GitHub Desktop.
Access Telldus API using curl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
[[ "${1^^}" == "GET" || "${1^^}" == "POST" ]] && [[ "${2}" =~ ^/.*$ ]] || exit 2 | |
urlencode () { | |
[[ -n "${1}" ]] && echo -n "${1}" | perl -p -e 's/([^A-Za-z0-9-._~])/sprintf("%%%02X", ord($1))/seg' | |
} | |
#oauth1 vars | |
consumer_key="..." | |
consumer_secret="..." | |
token="..." | |
token_secret="..." | |
signature_method="HMAC-SHA1" | |
t=$(date '+%s.%N') | |
timestamp="${t%%.*}" | |
nonce=$(md5sum <<< "$RANDOM-${t}" | cut -d ' ' -f 1) | |
request_method="${1^^}"; shift 1 | |
uri="${1}"; shift 1 | |
data="" | |
[[ ${#} -eq 0 ]] || { | |
if [[ "${request_method}" = "GET" || "${request_method}" = "DELETE" ]]; then | |
[[ ${#} -eq 1 ]] || exit 252 | |
data+="${1}" | |
else | |
[[ ${#} -eq 1 ]] && jq 'empty' <<< "${1}" || exit 252 | |
data=$(jq -r <<< "${1}" | sed -E 's@\.0+(,|$)@\1@' | jq -c -r '.') | |
fi | |
shift ${#} | |
} | |
url="https://api.telldus.com/${uri##/}"; encoded_url=$(urlencode "${url}") | |
encoded_oauth_sequence=$(urlencode "oauth_consumer_key=${consumer_key}&oauth_nonce=${nonce}&oauth_signature_method=${signature_method}&oauth_timestamp=${timestamp}&oauth_token=${token}&oauth_version=1.0") | |
[[ -z "${data}" ]] && encoded_data="" || encoded_data=$(urlencode "${data}&") | |
signature=$(echo -n "${request_method}&${encoded_url}&${encoded_data}${encoded_oauth_sequence}" | openssl dgst -sha1 -hmac "${consumer_secret}&${token_secret}" -binary | base64) | |
encoded_signature=$(urlencode "${signature}") | |
[[ -z "${data}" ]] || url+="?${data}" | |
request_url=() | |
if [[ "${request_method}" != "GET" || -n "${data}" ]]; then request_url+=('-X' "${request_method}"); fi | |
request_url+=("${url}") | |
curl -s "${request_url[@]}" \ | |
-H "Authorization: OAuth oauth_nonce=\"${nonce}\", oauth_timestamp=\"${timestamp}\", oauth_version=\"1.0\", oauth_signature_method=\"${signature_method}\", oauth_consumer_key=\"${consumer_key}\", oauth_token=\"${token}\", oauth_signature=\"${encoded_signature}\"" \ | |
-H 'Content-Type: application/json' \ | |
-H 'cache-control: no-cache' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment