Skip to content

Instantly share code, notes, and snippets.

@zed
Last active March 28, 2017 09:30
Show Gist options
  • Select an option

  • Save zed/5784d427a0c502e02205260dd311cebd to your computer and use it in GitHub Desktop.

Select an option

Save zed/5784d427a0c502e02205260dd311cebd to your computer and use it in GitHub Desktop.
shorten url using goo.gl
#!/usr/bin/env python3
"""Shorten a long url to the same https://goo.gl link.
Usage: goo.gl [<long-url>]
If the long-url is not provided, try the clipboard.
If pyperclip module is available. It copies the shorten url to clipboard.
Set GOOGLE_API_KEY envvar
"""
import json
import os
import shelve
import sys
from urllib.parse import urlparse, urlunparse
from urllib.request import Request, urlopen
try:
import pyperclip # $ pip install pyperclip
except ImportError:
pyperclip = None
__all__ = ['expand', 'lookup_analytics', 'shorten', 'shorten2same']
appname = 'shorten2same'
__version__ = '0.3.0'
api_url = 'https://www.googleapis.com/urlshortener/v1/url'
try:
api_key = os.environ['GOOGLE_API_KEY']
except KeyError:
import keychain # Pythonista on iOS
api_key = keychain.get_password('goo.gl', 'api_key')
assert api_key
headers = {'Content-Type': 'application/json',
'User-Agent': '{appname}/{__version__}'.format(**vars())}
def shorten(long_url):
"""Shorten *long_url* to https://goo.gl/..."""
data = json.dumps({'longUrl': long_url}).encode()
with urlopen(Request("{api_url}?key={api_key}".format(**globals()), data, headers)) as response:
return json.loads(response.read().decode())['id']
def shorten2same(long_url):
"""Shorten *long_url* to the same [cached on disk] http://goo.gl/..."""
with shelve.open(os.path.join(os.path.dirname(__file__), '.cache')) as fscache:
try:
data = fscache[long_url]
except KeyError:
data = fscache[long_url] = shorten(long_url)
return data
def expand(short_url):
"""Expand http://goo.gl *short_url*."""
url = "{api_url}?shortUrl={short_url}&key={api_key}".format(**vars())
with urlopen(Request(url, headers=headers)) as response:
return json.loads(response.read().decode())['longUrl']
def lookup_analytics(short_url):
"""Look up goo.gl *short_url* analytics."""
url = "{api_url}?shortUrl={short_url}&key={api_key}&projection=FULL".format_map({
**globals(), **locals()})
with urlopen(Request(url, headers=headers)) as response:
return json.loads(response.read().decode())
def main():
if len(sys.argv) == 2:
long_url = sys.argv[1]
elif pyperclip:
long_url = pyperclip.paste()
try:
purl = urlparse(long_url)
except NameError:
long_url = None
else:
long_url = urlunparse(purl) if purl.scheme.startswith('http') else None
if long_url is None:
sys.exit(__doc__)
url = shorten2same(long_url)
if pyperclip:
pyperclip.copy(url) # copy the shorten url to the clipboard
print('Copied the shorten url to the clipboard', file=sys.stderr)
print(url)
if __name__ == '__main__':
main()
from setuptools import find_packages, setup
from goo_gl import appname, __doc__, __version__
setup(
name=appname,
version=__version__,
description=__doc__.partition('\n')[0],
long_description=__doc__,
keywords='cli command-line',
author='jfs',
author_email='isidore.john.r@gmail.com',
url='https://gist.github.com/zed/5784d427a0c502e02205260dd311cebd',
license='MIT',
packages=find_packages(),
install_requires=['pyperclip'],
entry_points={'console_scripts': ['goo.gl=goo_gl:main']})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment