· 4 years ago · Mar 24, 2021, 11:40 AM
1#!/usr/bin/env bash
2
3# Imgur script by Bart Nagel <bart@tremby.net>
4# Improvements by Tino Sino <robottinosino@gmail.com>
5# Version 6 or more
6# I release this into the public domain. Do with it what you will.
7# The latest version can be found at https://github.com/tremby/imgur.sh
8
9# API Key provided by Bart;
10# replace with your own or specify yours as IMGUR_CLIENT_ID envionment variable
11# to avoid limits
12default_client_id=c9a6efb3d7932fd
13client_id="${IMGUR_CLIENT_ID:=$default_client_id}"
14
15# Function to output usage instructions
16function usage {
17 echo "Usage: $(basename $0) [<filename|URL> [...]]" >&2
18 echo
19 echo "Upload images to imgur and output their new URLs to stdout. Each one's" >&2
20 echo "delete page is output to stderr between the view URLs." >&2
21 echo
22 echo "A filename can be - to read from stdin. If no filename is given, stdin is read." >&2
23 echo
24 echo "If xsel, xclip, pbcopy, or clip is available," >&2
25 echo "the URLs are put on the X selection or clipboard for easy pasting." >&2
26}
27
28# Function to upload a path
29# First argument should be a content spec understood by curl's -F option
30function upload {
31 curl -s -H "Authorization: Client-ID $client_id" -H "Expect: " -F "image=$1" https://api.imgur.com/3/image.xml
32 # The "Expect: " header is to get around a problem when using this through
33 # the Squid proxy. Not sure if it's a Squid bug or what.
34}
35
36# Check arguments
37if [ "$1" == "-h" -o "$1" == "--help" ]; then
38 usage
39 exit 0
40elif [ $# -eq 0 ]; then
41 echo "No file specified; reading from stdin" >&2
42 exec "$0" -
43fi
44
45# Check curl is available
46type curl &>/dev/null || {
47 echo "Couldn't find curl, which is required." >&2
48 exit 17
49}
50
51clip=""
52errors=false
53
54# Loop through arguments
55while [ $# -gt 0 ]; do
56 file="$1"
57 shift
58
59 # Upload the image
60 if [[ "$file" =~ ^https?:// ]]; then
61 # URL -> imgur
62 response=$(upload "$file") 2>/dev/null
63 else
64 # File -> imgur
65 # Check file exists
66 if [ "$file" != "-" -a ! -f "$file" ]; then
67 echo "File '$file' doesn't exist; skipping" >&2
68 errors=true
69 continue
70 fi
71 response=$(upload "@$file") 2>/dev/null
72 fi
73
74 if [ $? -ne 0 ]; then
75 echo "Upload failed" >&2
76 errors=true
77 continue
78 elif echo "$response" | grep -q 'success="0"'; then
79 echo "Error message from imgur:" >&2
80 msg="${response##*<error>}"
81 echo "${msg%%</error>*}" >&2
82 errors=true
83 continue
84 fi
85
86 # Parse the response and output our stuff
87 url="${response##*<link>}"
88 url="[img]${url%%</link>*}[/img]"
89 delete_hash="${response##*<deletehash>}"
90 delete_hash="${delete_hash%%</deletehash>*}"
91 echo $url | sed 's/^http:/https:/'
92
93 # Append the URL to a string so we can put them all on the clipboard later
94 clip+="$url"
95 if [ $# -gt 0 ]; then
96 clip+=$'\n'
97 fi
98done
99
100
101if $errors; then
102 exit 1
103fi