Skip to content

Instantly share code, notes, and snippets.

@ragingwind ragingwind/shorten.py
Last active Jul 7, 2018

Embed
What would you like to do?
Shorten URL with markdown for Alfred. Added title to origin https://github.com/hzlzh/Alfred-Workflows
'''
Shorten URL v1.5
Github: https://github.com/hzlzh/Alfred-Workflows
Author: hzlzh (hzlzh.dev@gmail.com)
Twitter: @hzlzh
Blog: https://zlz.im/Alfred-Workflows/
'''
# encoding: utf-8
from __future__ import print_function
import urllib
import urllib2
import json
import sys
import re
def getTitle(url):
req = urllib2.Request(url, headers={'User-Agent' : "Alred"})
res = urllib2.urlopen(req)
html = res.read().decode('utf-8').strip()
title = html.split('<title>')[1].split('</title>')[0]
if title:
return title.strip()
else:
return url
def getLink(type,service,url):
if (('http' in url) == False):
url = 'http://'+url
if type == 'goo.gl':
terms = urllib.quote_plus(url.strip())
data = json.dumps({"longUrl": url})
clen = len(data)
req = urllib2.Request(service,data,{'Content-Type': 'application/json', 'Content-Length': clen})
f = urllib2.urlopen(req)
data = f.read()
output = json.loads(data)["id"]
elif type == 'git.io':
match = re.search('^(https?:\/\/)?(gist\.)?github.com', url)
if match:
terms = urllib.quote_plus(url.strip())
data = urllib2.urlopen(url=service, data='url=' + terms)
output = dict(data.info())['location']
else:
output = 'URL must be from github.com'
else:
try:
terms = urllib.quote_plus(url.strip())
url = service + terms
data = urllib2.urlopen(url).read()
except Exception, e:
print('')
if type == 'bit.ly':
result = json.loads(data)
if(result["status_code"] == 500):
output = result["status_txt"]
else:
output = result["data"]["url"]
elif type == 'j.mp':
result = json.loads(data)
if(result["status_code"] == 500):
output = result["status_txt"]
else:
output = result["data"]["url"]
elif type == 't.cn':
result = json.loads(data)
if('error_code' in result.keys()):
output = result["error"]
else:
output = result["urls"][0]["url_short"]
elif type == 'is.gd':
result = json.loads(data)
if('errorcode' in result.keys()):
output = result["errormessage"]
else:
output = result["shorturl"]
elif type == 'v.gd':
result = json.loads(data)
if('errorcode' in result.keys()):
output = result["errormessage"]
else:
output = result["shorturl"]
return output
temp = '{query}'
response = json.loads(temp)
type = response['type']
service = response['api_url']
url = response['long_url']
title = getTitle(url)
last_output = getLink(type,service,url)
shorten = "[" + title + "](" + last_output + ")"
if ('http' in last_output):
print(shorten)
else:
print('Error: '+ last_output, end='')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.