getvods/getvods.sh

75 lines
2.9 KiB
Bash

#!/bin/bash
# ${1} (optional) username to search VODs of
# ${1} is a string with error reason stated
# ${2} is an optional string to report a different error status
CFG_DIR="${HOME}/.config/getvods"
on_fail(){
printf "last ran command error status: %s\n" "${2:-${?}}"
printf "error: %s\n" "${1}"
exit 2
}
# twitch api credentials
client_id="$(cat "${CFG_DIR}/client_id")"
client_secret="$(cat "${CFG_DIR}/client_secret")"
get_token(){
curl -s -X POST https://id.twitch.tv/oauth2/token -d "client_id=${client_id}" -d "client_secret=${client_secret}" -d "grant_type=client_credentials" > "${CFG_DIR}/token.json" || {
last_err="${?}"
rm "${CFG_DIR}/token.json" 2>/dev/null
on_fail "couldn't get token (curl error)" "${last_err}"
}
bc -l <<< "$(date +%s) + $(grep -o "expires_in\":[0-9]\+" "${CFG_DIR}/token.json" | awk -F : '{print $2}')" > "${CFG_DIR}/expiration.txt" || {
last_err="${?}"
rm "${CFG_DIR}/expiration.txt" 2>/dev/null
on_fail "couldn't save expiration date" "${last_err}"
}
}
# get access token
[ -f "${CFG_DIR}/token.json" ] && [ -f "${CFG_DIR}/expiration.txt" ] && {
[ "$(cat "${CFG_DIR}/expiration.txt")" -le "$(date +%s)" ] && get_token
} || {
get_token
}
access_token="$(grep -o "access_token\":\"[a-zA-Z0-9]\+" "${CFG_DIR}/token.json" | awk -F \" '{print $3}')"
[ -z "${access_token}" ] && {
last_err="${?}"
rm "${CFG_DIR}/token.json"
on_fail "couldn't get token (token empty)" "${last_err}"
}
[ ! -z "${1}" ] && login="${1}" || read -p 'type in username >' login
# get user id
[ ! -f "${CFG_DIR}/userlist.txt" ] || [ "${login}" != "$(grep "${login}" "${CFG_DIR}/userlist.txt" | awk -F ":|," '{print $4}')" ] && {
user_response="$(curl -s -G -X GET "https://api.twitch.tv/helix/users" -d "login=${login}" -H "Authorization: Bearer ${access_token}" -H "client-id: ${client_id}")"
[ "${?}" -gt 0 ] && {
last_err="${?}"
on_fail "couldn't get user_id (curl error)" "${last_err}"
}
parsed_user_response="$(grep -o "id\":\"[0-9]\+\",\"login\":\"[a-zA-Z0-9]\+" <<< "${user_response}")"
[ "${?}" -gt 0 ] && {
last_err="${?}"
on_fail "couldn't get user_id (user_id empty)" "${last_err}"
}
unset user_response
sed 's/\"//g' <<< "${parsed_user_response}" >> "${CFG_DIR}/userlist.txt"
unset parsed_user_response
}
user_id="$(grep "${login}" "${CFG_DIR}/userlist.txt" | awk -F ":|," '{print $2}')"
# save json with first 20 videos tied to the user id we just got
curl -s -G -X GET "https://api.twitch.tv/helix/videos" -d "type=archive" -d "user_id=${user_id}" -H "Authorization: Bearer ${access_token}" -H "client-id: ${client_id}"\
> "${CFG_DIR}/streamarchives.json"
sed -i 's/^{"data":\[\|}],"pagination":{"cursor":"[a-zA-Z0-9]\+"}}$//g' "${CFG_DIR}/streamarchives.json"
unset client_secret client_id user_id last_err
# TODO:
# - read title, duration and url of last 20 VODS and present them to user
# - get a choice from user and save the url of that selection to the clipboard