Created
February 7, 2011 14:36
-
-
Save jakubjedelsky/814449 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
# | |
# Jakub Jedelsky <[email protected]> | |
# | |
# Simple UTL shortener using google API (outcome | |
# address is goo.gl). | |
# | |
# GNU GPLv2+ | |
# | |
import urllib2 | |
import sys | |
try: | |
import json | |
except ImportError: | |
import simplejson as json | |
def sendLongUrl(l_url): | |
"""Send long url to google API and return its response.""" | |
host = "https://www.googleapis.com/urlshortener/v1/url" | |
data = {"longUrl" : l_url} | |
header = { | |
"Content-type" : "Application/json", | |
"User-Agent" : "i am a goopy" | |
} | |
data_json = json.dumps(data) | |
req = urllib2.Request(host, data_json, header) | |
response = urllib2.urlopen(req).read() | |
return response | |
def readLongUrl(json_data): | |
"""Parse data returned by google API.""" | |
out = json.loads(json_data) | |
return out['id'] | |
def main(): | |
if len(sys.argv) <= 1: | |
try: | |
import gtk | |
clipboard = gtk.clipboard_get() | |
c_text = clipboard.wait_for_text() | |
if not c_text: | |
print "There isn't a txt in clipboard; exiting..." | |
sys.exit(1) | |
# we can use only "one-line text" | |
s_text = c_text.split('\n') | |
if len(s_text) > 1: | |
print "Your text has more than one line; exiting..." | |
sys.exit(1) | |
url = c_text | |
except ImportError: | |
print "Sorry, can't include gtk; exiting..." | |
sys.exit(1) | |
else: | |
if sys.argv[1] == '-h': | |
print """Usage: goo.py [option] URL | |
Options: | |
-h prints this help | |
URL is a long url which you want to shorted.""" | |
sys.exit(0) | |
else: | |
url = sys.argv[1] | |
api_result = sendLongUrl(url) | |
print readLongUrl(api_result) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment