PageRenderTime 28ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/XSSer/post/shorter.py

https://bitbucket.org/badc0re/xsser_gsoc
Python | 76 lines | 43 code | 5 blank | 28 comment | 8 complexity | 749eb86cc244ebf8a5b7c066f1a8847a MD5 | raw file
  1. #!/usr/bin/python
  2. # -*- coding: iso-8859-15 -*-
  3. """
  4. $Id$
  5. This file is part of the xsser project, http://xsser.sourceforge.net.
  6. Copyright (c) 2011/2012 psy <root@lordepsylon.net> - <epsylon@riseup.net>
  7. xsser is free software; you can redistribute it and/or modify it under
  8. the terms of the GNU General Public License as published by the Free
  9. Software Foundation version 3 of the License.
  10. xsser is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  12. FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  13. details.
  14. You should have received a copy of the GNU General Public License along
  15. with xsser; if not, write to the Free Software Foundation, Inc., 51
  16. Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  17. -------
  18. Post processing filter to make reservations on shortered links.
  19. """
  20. import urllib
  21. import pycurl
  22. from cStringIO import StringIO
  23. from BeautifulSoup import BeautifulSoup
  24. class ShortURLReservations(object):
  25. #options = [['-foo!', 'do stuff']]
  26. def __init__(self, service='tinyurl'):
  27. self._service = service
  28. self._parse_shortener()
  29. self._extra = {}
  30. def _parse_shortener(self):
  31. """
  32. List of valid links shorterers
  33. """
  34. if self._service == 'tinyurl' or not self._service:
  35. self._url = 'http://tinyurl.com/create.php'
  36. self._par = 'url'
  37. self._method = 'get'
  38. elif self._service == 'is.gd':
  39. self._url = 'http://is.gd/create.php'
  40. self._par = 'url'
  41. self._method = 'post'
  42. def process_url(self, url):
  43. dest = urllib.urlencode({self._par: url})
  44. out = StringIO()
  45. c = pycurl.Curl()
  46. if self._method == 'post':
  47. c.setopt(c.POST, 1)
  48. c.setopt(c.POSTFIELDS, dest)
  49. target = self._url
  50. else:
  51. target = self._url + '?' + dest
  52. c.setopt(c.URL, target)
  53. c.setopt(c.FOLLOWLOCATION, 1)
  54. c.setopt(c.WRITEFUNCTION, out.write)
  55. c.perform()
  56. c.close()
  57. soup = BeautifulSoup(out.getvalue())
  58. if self._service == 'tinyurl':
  59. return soup.findAll('blockquote')[1].findAll('a')[0]['href']
  60. elif self._service == 'is.gd':
  61. return soup.findAll('input', {'id':'short_url'})[0]['value']
  62. if __name__ == "__main__":
  63. shortener = ShortURLReservations('tinyurl')
  64. print shortener.process_url('http://slashdot.org?foo')
  65. shortener = ShortURLReservations('is.gd')
  66. print shortener.process_url('http://slashdot.org?foo')