Skip to content

Instantly share code, notes, and snippets.

@KaiaKitten
Last active December 16, 2023 05:43
Show Gist options
  • Save KaiaKitten/6db91d4221651c4fec653189939c5273 to your computer and use it in GitHub Desktop.
Save KaiaKitten/6db91d4221651c4fec653189939c5273 to your computer and use it in GitHub Desktop.
Uploads files passed it to personal Imgur account. Also auto converts webp and webm files to png and gif.
#!/bin/bash
refresh_token="<insert_refresh_token_here>"
client_id="<insert_client_id_here>"
client_secret="<insert_client_secret_here>"
#Check to make sure any files where passed in.
if [ $# -eq 0 ]; then
echo "No file specified" >&2
exit 16
fi
# Read file storing last acess token
read token < $HOME/.imgtoken.txt
check_token(){
# Check is access toke has expired, if so refresh it and update file storing token.
error=$(curl -s -X POST -H "Authorization: Bearer $token" https://api.imgur.com/3/image.xml)
if [ $(echo $error | grep -c "The access token provided is invalid") -gt 0 ]; then
retoken=$(curl -s --data "refresh_token=$refresh_token&client_id=$client_id&client_secret=$client_secret&grant_type=refresh_token" https://api.imgur.com/oauth2/token)
token=$(echo $retoken | jq -r ".access_token")
echo "Refreshed token"
echo $token > .imgtoken.txt
fi
}
check_file(){
# Check file exists
if [ ! -f "$file" ]; then
echo "File '$file' doesn't exist; skipping" >&2
continue
fi
}
check_ext(){
# Check if image is a webp file, if so convert to png.
# Imgur does not support webp as of writing.
if [[ $file =~ \.webp$ ]]; then
echo "Converting file"
mogrify -format png $file
file="${file/webp/png}"
fi
# Check if image is a webm file, if so convert to gif.
# Imgur does not support webm as of writing.
if [[ $file =~ \.webm$ ]]; then
echo "Converting file"
ffmpeg -i $file ${file/webm/gif}
file="${file/webm/gif}"
fi
}
upload_image(){
# Upload the file, print url and set url to clip board
echo "Uploading file"
respone=$(curl -X POST -H "Authorization: Bearer $token" -F "image=@$file" https://api.imgur.com/3/image.xml)
url=$(echo $respone | sed -n -e 's/.*<link>\(.*\)<\/link>.*/\1/p')
echo $url
echo $url | xclip -sel clip
}
upload(){
# Combine all functions in order
check_file
check_ext
check_token
upload_image
}
# Iterate over every file pass in and upload them all.
while [ $# -gt 0 ]; do
file="$1"
shift
upload
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment