Browse Source

[shortener] separate services related code in functions

Signed-off-by: r4sas <r4sas@i2pmail.org>
dependabot/add-v2-config-file
R4SAS 5 years ago
parent
commit
ebfe0c48a0
Signed by: r4sas
GPG Key ID: 66F6C87B98EBCFE2
  1. 237
      pbincli/api.py

237
pbincli/api.py

@ -111,133 +111,150 @@ class Shortener:
self.session, self.proxy = _config_requests(settings) self.session, self.proxy = _config_requests(settings)
def getlink(self, url): def getlink(self, url):
if self.api == 'yourls': # that is api -> function mapper for running service-related function when getlink() used
request = {'action': 'shorturl', 'format': 'json', 'url': url} servicesList = {
request.update(self.auth_args) 'yourls': self._yourls,
'clckru': self._clckru,
'tinyurl': self._tinyurl,
'isgd': self._gd,
'vgd': self._gd,
'cuttly': self._cuttly
}
# run function selected by choosen API
servicesList[self.api](url)
def _yourls(self,url):
request = {'action': 'shorturl', 'format': 'json', 'url': url}
request.update(self.auth_args)
result = self.session.post( result = self.session.post(
url = self.apiurl, url = self.apiurl,
proxies = self.proxy, proxies = self.proxy,
data = request) data = request)
try:
result.raise_for_status()
except HTTPError:
try: try:
result.raise_for_status()
except HTTPError:
try:
response = result.json()
except ValueError:
PBinCLIError("YOURLS: Unable parse response. Received (size = {}):\n{}".format(len(result.text), result.text))
else:
PBinCLIError("YOURLS: Received error from API: {} with JSON {}".format(result, response))
else:
response = result.json() response = result.json()
except ValueError:
PBinCLIError("YOURLS: Unable parse response. Received (size = {}):\n{}".format(len(result.text), result.text))
else:
PBinCLIError("YOURLS: Received error from API: {} with JSON {}".format(result, response))
else:
response = result.json()
if {'status', 'statusCode', 'message'} <= set(response.keys()): if {'status', 'statusCode', 'message'} <= set(response.keys()):
if response['status'] == 'fail': if response['status'] == 'fail':
PBinCLIError("YOURLS: Received error from API: {}".format(response['message'])) PBinCLIError("YOURLS: Received error from API: {}".format(response['message']))
if not 'shorturl' in response: if not 'shorturl' in response:
PBinCLIError("YOURLS: Unknown error: {}".format(response['message'])) PBinCLIError("YOURLS: Unknown error: {}".format(response['message']))
else:
print("Short Link:\t{}".format(response['shorturl']))
else: else:
PBinCLIError("YOURLS: No status, statusCode or message fields in response! Received:\n{}".format(response)) print("Short Link:\t{}".format(response['shorturl']))
else:
PBinCLIError("YOURLS: No status, statusCode or message fields in response! Received:\n{}".format(response))
elif self.api == 'clckru':
request = {'url': url}
try: def _clckru(self, url):
result = self.session.post( request = {'url': url}
url = "https://clck.ru/--",
proxies = self.proxy,
data = request)
print("Short Link:\t{}".format(result.text))
except Exception as ex:
PBinCLIError("clck.ru: unexcepted behavior: {}".format(ex))
elif self.api == 'tinyurl': try:
request = {'url': url} result = self.session.post(
url = "https://clck.ru/--",
proxies = self.proxy,
data = request)
print("Short Link:\t{}".format(result.text))
except Exception as ex:
PBinCLIError("clck.ru: unexcepted behavior: {}".format(ex))
try:
result = self.session.post(
url = "https://tinyurl.com/api-create.php",
proxies = self.proxy,
data = request)
print("Short Link:\t{}".format(result.text))
except Exception as ex:
PBinCLIError("TinyURL: unexcepted behavior: {}".format(ex))
elif self.api == 'isgd' or self.api == 'vgd': def _tinyurl(self, url):
request = { request = {'url': url}
'format': 'json',
'url': url,
'logstats': 0 # we don't want use any statistics
}
headers = { 'User-Agent': self.useragent}
try: try:
result = self.session.post( result = self.session.post(
url = self.apiurl + "create.php", url = "https://tinyurl.com/api-create.php",
headers = headers, proxies = self.proxy,
proxies = self.proxy, data = request)
data = request) print("Short Link:\t{}".format(result.text))
except Exception as ex:
PBinCLIError("TinyURL: unexcepted behavior: {}".format(ex))
response = result.json()
if 'shorturl' in response: def _gd(self, url):
print("Short Link:\t{}".format(response['shorturl'])) request = {
else: 'format': 'json',
PBinCLIError("{}: got error {} from API: {}".format( 'url': url,
"is.gd" if self.api == 'isgd' else 'v.gd', 'logstats': 0 # we don't want use any statistics
response['errorcode'], }
response['errormessage'])) headers = { 'User-Agent': self.useragent}
except Exception as ex: try:
PBinCLIError("{}: unexcepted behavior: {}".format( result = self.session.post(
url = self.apiurl + "create.php",
headers = headers,
proxies = self.proxy,
data = request)
response = result.json()
if 'shorturl' in response:
print("Short Link:\t{}".format(response['shorturl']))
else:
PBinCLIError("{}: got error {} from API: {}".format(
"is.gd" if self.api == 'isgd' else 'v.gd', "is.gd" if self.api == 'isgd' else 'v.gd',
ex)) response['errorcode'],
response['errormessage']))
elif self.api == 'cuttly': except Exception as ex:
request = { PBinCLIError("{}: unexcepted behavior: {}".format(
'url': url, "is.gd" if self.api == 'isgd' else 'v.gd',
'domain': 0 ex))
}
try:
result = self.session.post(
url = "https://cutt.ly/scripts/shortenUrl.php",
proxies = self.proxy,
data = request)
print("Short Link:\t{}".format(result.text))
except Exception as ex:
PBinCLIError("cutt.ly: unexcepted behavior: {}".format(ex))
'''
# That code needs testing. API requires username and apiKey or accessToken to work.
elif self.api == 'bitly':
request = {'url': url}
headers = {'X-Requested-With': 'XMLHttpRequest'}
try: def _cuttly(self, url):
result = self.session.post( request = {
url = "https://bitly.com/", 'url': url,
headers = headers, 'domain': 0
proxies = self.proxy, }
data = request)
response = result.json() try:
if response['data'] and response['status_code'] == 200: result = self.session.post(
print("Short Link:\t{}".format(response['data']['anon_shorten']['link'])) url = "https://cutt.ly/scripts/shortenUrl.php",
elif response['status_txt']: proxies = self.proxy,
errcode = response['status_txt'] or 'DEFAULT' data = request)
friendlyError = { print("Short Link:\t{}".format(result.text))
'RATE_LIMIT_EXCEEDED': 'Whoa - you\'ve exceeded your quota. Create a free account to keep shortening.', except Exception as ex:
'INVALID_ARG_URL': 'Unable to shorten that link. It is not a valid url.', PBinCLIError("cutt.ly: unexcepted behavior: {}".format(ex))
'INVALID_ARG_LONGURL': 'Unable to shorten that link. It is not a valid url.',
'ALREADY_A_BITLY_LINK': 'That is already a Bitly link',
'UNKNOWN_ERROR': 'Woops. Something went wrong. Please try again.', # [WIP] That code needs testing. API requires username and apiKey or accessToken to work.
'DEFAULT': 'An error occurred' def _bitly(self, url):
} request = {'url': url}
PBinCLIError("bitly: got error from API: {}".format(friendlyError[errcode])) headers = {'X-Requested-With': 'XMLHttpRequest'}
except Exception as ex:
PBinCLIError("bitly: unexcepted behavior: {}".format(ex)) try:
''' result = self.session.post(
url = "https://bitly.com/",
headers = headers,
proxies = self.proxy,
data = request)
response = result.json()
if response['data'] and response['status_code'] == 200:
print("Short Link:\t{}".format(response['data']['anon_shorten']['link']))
elif response['status_txt']:
errcode = response['status_txt'] or 'DEFAULT'
friendlyError = {
'RATE_LIMIT_EXCEEDED': 'Whoa - you\'ve exceeded your quota. Create a free account to keep shortening.',
'INVALID_ARG_URL': 'Unable to shorten that link. It is not a valid url.',
'INVALID_ARG_LONGURL': 'Unable to shorten that link. It is not a valid url.',
'ALREADY_A_BITLY_LINK': 'That is already a Bitly link',
'UNKNOWN_ERROR': 'Woops. Something went wrong. Please try again.',
'DEFAULT': 'An error occurred'
}
PBinCLIError("bitly: got error from API: {}".format(friendlyError[errcode]))
except Exception as ex:
PBinCLIError("bitly: unexcepted behavior: {}".format(ex))

Loading…
Cancel
Save