2017-08-12 21:32:56 +02:00
|
|
|
import requests
|
2014-10-27 16:29:04 -06:00
|
|
|
|
|
|
|
class URLShortener (object):
|
|
|
|
|
|
|
|
def __init__ (self, *args, **kwargs):
|
|
|
|
#Stub out arguments, silly object. :(
|
|
|
|
return super(URLShortener, self).__init__()
|
|
|
|
|
|
|
|
def shorten (self, url):
|
|
|
|
if self.created_url(url):
|
|
|
|
return url
|
|
|
|
else:
|
|
|
|
return self._shorten(url)
|
|
|
|
|
|
|
|
def _shorten (self, url):
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
def created_url (self, url):
|
|
|
|
"""Returns a boolean indicating whether or not this shortener created a provided url"""
|
|
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
def unshorten(self, url):
|
2017-09-18 10:38:20 +02:00
|
|
|
try:
|
2017-09-22 17:18:38 +02:00
|
|
|
r=requests.head(url)
|
2017-09-22 17:30:09 +02:00
|
|
|
if 'location' in r.headers.keys():
|
|
|
|
if 'dropbox.com' in r.headers['location']:
|
|
|
|
return handle_dropbox(r.headers['location'])
|
|
|
|
else:
|
|
|
|
return r.headers['location']
|
2017-12-11 21:07:57 +01:00
|
|
|
else: # if the head method does not work, use get instead. Performance may decrease
|
2017-12-12 16:32:12 +01:00
|
|
|
r=requests.get(url, allow_redirects=False, stream=True)
|
|
|
|
# release the connection without downloading the content, we only need the response headers
|
|
|
|
r.close()
|
2017-12-11 21:07:57 +01:00
|
|
|
return r.headers['location']
|
2017-09-18 10:38:20 +02:00
|
|
|
except:
|
|
|
|
return url #we cannot expand
|
2017-09-22 17:30:09 +02:00
|
|
|
|
|
|
|
def handle_dropbox(url):
|
|
|
|
if url.endswith("dl=1"):
|
|
|
|
return url
|
|
|
|
else:
|
|
|
|
return url.replace("dl=0", "dl=1")
|