Last active
August 29, 2015 14:12
-
-
Save joech4n/d6668021bcd0bb30f9e7 to your computer and use it in GitHub Desktop.
Shorten link with Bit.ly via Python
This file contains 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
#!/usr/bin/env python | |
# Requires config file at ~/.burl.py: | |
# [Defaults] | |
# login = MYLOGINNAMEHERE | |
# key = MYTOKENHERE | |
# Shortens URL via Bit.ly | |
# Input: URL from clipboard OR CLI argument | |
# Action: The shortened URL is put on the clipboard, ready for pasting. You'll be notified via growlnotify that your link is ready. | |
import argparse | |
import ConfigParser | |
import os | |
import subprocess | |
import sys | |
import urllib | |
from urlparse import urlparse | |
DEFAULT_CONFIG_PATH = '~/.' + os.path.basename(__file__) | |
# From http://blog.vwelch.com/2011/04/combining-configparser-and-argparse.html | https://gist.github.com/joech4n/c7a8c2a8c9ba0d5a6891 | |
conf_parser = argparse.ArgumentParser(description='''Generate bit.ly URL | |
API login and key is sourced from''' + DEFAULT_CONFIG_PATH + ''' by default, but can be overridden with --login and --key. Format of config file: | |
[Defaults] | |
login = MYLOGINNAMEHERE | |
key = MYTOKENHERE | |
''', | |
# Turn off help, so we print all options in response to -h | |
add_help=False | |
) | |
conf_parser.add_argument("-c", "--conf_file", | |
help="Specify config file", metavar="FILE", default=os.path.expanduser('~') + '/.' + os.path.basename(__file__)) | |
args, remaining_argv = conf_parser.parse_known_args() | |
defaults = { | |
"option1" : "some default", | |
"option2" : "some other default", | |
} | |
if args.conf_file: | |
config = ConfigParser.SafeConfigParser() | |
config.read([args.conf_file]) | |
defaults = dict(config.items("Defaults")) | |
# Don't surpress add_help here so it will handle -h | |
parser = argparse.ArgumentParser( | |
# Inherit options from config_parser | |
parents=[conf_parser], | |
# print script description with -h/--help | |
description=__doc__, | |
# Don't mess with format of description | |
formatter_class=argparse.RawDescriptionHelpFormatter, | |
) | |
parser.set_defaults(**defaults) | |
parser.add_argument('--login', help='If not specified, will be sourced from ' + DEFAULT_CONFIG_PATH) | |
parser.add_argument('--key', help='If not specified, will be sourced from ' + DEFAULT_CONFIG_PATH) | |
parser.add_argument('longUrl', nargs='?') | |
args = parser.parse_args(remaining_argv) | |
if args.key is None: | |
sys.exit('ERROR: Cannot load key from '+DEFAULT_CONFIG_PATH+' and --key not specified. An API KEY must be provided via ' + DEFAULT_CONFIG_PATH + ' or --key') | |
else: | |
API_KEY = args.key | |
if args.login is None: | |
sys.exit('ERROR: Cannot load login from '+DEFAULT_CONFIG_PATH+' and --login not specified. A login must be provided via ' + DEFAULT_CONFIG_PATH + ' or --key') | |
else: | |
LOGIN = args.login | |
# Get the URL of the frontmost Firefox window/tab though AppleScript. | |
applescript = '''tell application "Firefox" | |
set myFirefox to properties of front window as list | |
get item 3 of myFirefox | |
end tell''' | |
if args.longUrl is None: | |
#input = popen("osascript -e '" + applescript + "'").read().strip() # Get URL from tab via AppleScript | |
input = os.popen('pbpaste', "r").read().strip() | |
source = 'clipboard' | |
else: | |
input = args.longUrl | |
source = 'CLI argument' | |
assert urlparse(input).netloc, "ERROR: Invalid URL" # Verify Long URL | |
# Encode input | |
url = urllib.quote_plus(input) | |
# Get the shortened URL from bit.ly. | |
bitlyCall = 'http://api.bit.ly/v3/shorten?longUrl=' + url + '&login=' + LOGIN + '&apiKey=' + API_KEY + '&format=txt' | |
shortUrl = subprocess.check_output(['curl', '--stderr', '/dev/null', bitlyCall]) | |
# Put the shortened URL on the clipboard. | |
os.popen('pbcopy', 'w').write(shortUrl) | |
# Display growl notification | |
cmd = '/usr/local/bin/growlnotify -i HTML -m \'Shortened ' + input + 'to \n' + shortUrl + '\'' | |
subprocess.call(['/usr/local/bin/growlnotify', '-m ', input, shortUrl]) | |
print 'Shortened URL from ' + source + ': ' + shortUrl |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment