bitly.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from __future__ import unicode_literals
  2. import sys
  3. from terroroftinytown.client.errors import UnexpectedNoResult
  4. from terroroftinytown.services.base import BaseService
  5. from terroroftinytown.services.status import URLStatus
  6. from terroroftinytown.six.moves.urllib import parse as urlparse
  7. from terroroftinytown.services.rand import HashRandMixin
  8. class BitlyService(BaseService):
  9. def process_redirect(self, response):
  10. if response.status_code == 302:
  11. if 'location' not in response.headers:
  12. raise UnexpectedNoResult()
  13. url = urlparse.urlparse(response.headers['location'])
  14. if url.scheme != "http" or url.netloc != "bit.ly" or url.path != "/a/warning":
  15. raise UnexpectedNoResult("Unexpected Location header after HTTP status 302")
  16. if sys.version_info[0] == 2:
  17. query = urlparse.parse_qs(url.query.encode('latin-1'))
  18. else:
  19. query = urlparse.parse_qs(url.query)
  20. if not ("url" in query and len(query["url"]) == 1) or not ("hash" in query and len(query["hash"]) == 1):
  21. raise UnexpectedNoResult("Unexpected Location header after HTTP status 302")
  22. if query["hash"][0] != self.current_shortcode:
  23. raise UnexpectedNoResult("Hash mismatch for HTTP status 302")
  24. if sys.version_info[0] == 2:
  25. unshortened_url = query["url"][0].decode('latin-1')
  26. else:
  27. unshortened_url = query["url"][0]
  28. return (URLStatus.ok, unshortened_url, None)
  29. else:
  30. return BaseService.process_redirect(self, response)
  31. class Bitly6Service(HashRandMixin, BitlyService):
  32. def get_shortcode_width(self):
  33. return 6