spotify-dl/lib/get_token.sh

23 lines
905 B
Bash
Executable File

#!/bin/bash
source .env
## Check if we have a non expired token in cache, or get it
if [[ -f .token_cache ]]; then
cached_timestamp=$(cat .token_cache | jq .expires_time)
timestamp=$(date +%s)
if [[ $timestamp -lt $cached_timestamp ]]; then
sp_token=$(cat .token_cache | jq -r .token)
[[ $sp_token == "null" ]] && unset sp_token
fi
fi
if [[ ! $sp_token ]]; then
base64_id="$(echo -n $sp_client_id:$sp_client_secret | base64 -w 0)"
sp_token=$(curl -s --location --request POST 'https://accounts.spotify.com/api/token' --header "Authorization: Basic $base64_id" --data-urlencode 'grant_type=client_credentials' | jq -r .access_token)
timestamp=$(date +%s)
((timestamp=timestamp+3600))
echo -e "{\n\"token\": \"$sp_token\",\n\"expires_time\": $timestamp\n}" | jq . > .token_cache
fi
echo -n $sp_token