Skip to content

Instantly share code, notes, and snippets.

@0x6362

0x6362/giphy-grab

Created Aug 25, 2020
Embed
What would you like to do?
#!/usr/bin/env bash
set -e
usage() {
echo "giphy-grab [-f|--force] [-s|--skip-title] [-o|--output] <url>"
echo " --force: overwrite output file if it exists"
echo " --skip-title: don't fetch GIF name from GIPHY"
echo " --output: filename or destination folder for GIF"
exit 1
}
POSITIONAL=()
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-h|--help)
usage
shift
shift
;;
-f|--force)
OVERWRITE="true"
shift
;;
-s|--skip-title)
SKIP_TITLE="true"
shift
;;
-o|--output)
OUTPUT="$2"
shift
shift
;;
*) # unknown, save for later unpacking
POSITIONAL+=("$1")
shift
;;
esac
done
set -- "${POSITIONAL[@]}" # restore unflagged params
if (( ${#POSITIONAL[@]} < 1 )); then
usage
fi
extract_id() {
echo "$1" | grep -E -o "\b[a-zA-Z0-9]{10,20}\b"
}
fetch_title() {
curl -L -s "https://giphy.com/gifs/$1" \
| grep -E -o "<title>.+</title>" \
| sed -E 's/\<[^>]+\>//g' \
| sed -E 's/ GIF.* - Find &amp; Share on GIPHY//'
}
URL="$1"
ID=$(extract_id "$URL")
GIF_URL="http://i.giphy.com/media/${ID}/giphy.gif"
if [[ "$SKIP_TITLE" ]] && [[ -z "$OUTPUT" ]]; then
echo "-o|--output must be used when -s|--skip-title flag is set" >&2
exit 1
fi
if [[ -z "$SKIP_TITLE" ]]; then
COMPUTED_NAME=$(fetch_title "$ID")
COMPUTED_NAME="${COMPUTED_NAME}.gif"
fi
if [[ "$OUTPUT" ]]; then
# must be passed as last argument
if [[ -d "$OUTPUT" ]] && [[ "$COMPUTED_NAME" ]]; then
OUTPUT="${OUTPUT}/${COMPUTED_NAME}"
fi
else
OUTPUT="$COMPUTED_NAME"
fi
cmd=(curl -L --output "$OUTPUT" "$GIF_URL")
if [[ -e "$OUTPUT" ]] && [[ -z "$OVERWRITE" ]]; then
echo "$OUTPUT exists and -f|--force not set. Exiting"
exit 1
fi
echo "Destination URL: $URL | Output: ${OUTPUT}"
#echo "${cmd[@]}"
"${cmd[@]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.