Created
May 13, 2014 17:13
-
-
Save naftulikay/12d526160b987cfa106d to your computer and use it in GitHub Desktop.
AutoKey Bit.ly Link Shortener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Bit.ly URL Shortener for AutoKey | |
# | |
# On Ubuntu, you must run: | |
# | |
# sudo apt-get install xclip python-pip | |
# | |
# and | |
# | |
# sudo pip install requests | |
BITLY_API_KEY="YOUR_BITLY_API_KEY" | |
from subprocess import Popen as popen, PIPE | |
import re | |
import sys | |
if subprocess.call(['which', 'xclip']) != 0: | |
subprocess.call(['notify-send', '-u', 'normal', '-t', '15000', | |
'-i', 'error', "Error Shortening URL", | |
"Please install the 'xclip' program."]) | |
try: | |
import requests | |
except ImportError: | |
subprocess.call(['notify-send', '-u', 'normal', '-t', '15000', | |
'-i', 'error', "Error Shortening URL", | |
"Please install the Python 'requests' library."]) | |
sys.exit(1) | |
try: | |
value = clipboard.get_selection() | |
except Exception: | |
value = "" | |
is_valid_url = lambda u: re.match( | |
r'^(?:http|ftp)s?://' # http:// or https:// | |
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... | |
r'localhost|' #localhost... | |
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip | |
r'(?::\d+)?' # optional port | |
r'(?:/?|[/?]\S+)$', u, re.IGNORECASE | |
) is not None | |
is_bitly_url = lambda u: re.match( | |
r'^https?://(?:bit\.ly|j\.mp)/(?:[a-z]+)$', | |
u, re.IGNORECASE | |
) is not None | |
if is_valid_url(value) and not is_bitly_url(value): | |
# if value is real URL and not | |
r = requests.get("https://api-ssl.bitly.com/v3/shorten", params={ | |
'access_token': BITLY_API_KEY, | |
'longUrl': value | |
}) | |
if r.ok and r.json()['status_code'] == 200: | |
# if it worked, get us a nice HTTPS link | |
result = re.sub(r'(?ui)(?<=^http)(?=:)', "s", r.json()['data']['url']) | |
print "Shortened URL: %s" % (result,) | |
# set clipboard | |
popen(["xclip", "-selection", "clipboard"], stdin=PIPE).communicate(input=result) | |
# show notification | |
subprocess.call(['notify-send', '-u', 'normal', '-t', '15000', | |
'-i', 'document-export', "Link Shortened to Clipboard", | |
"Short Link: %s" % (result,)]) | |
else: | |
print "Unable to shorten url, result from server: %s" % (r.json(),) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment