giphy.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. """
  2. Giphy Tag
  3. ---------
  4. This implements a Liquid-style Giphy tag for Pelican.
  5. IMPORTANT: You have to request a production API key from giphy `here <https://api.giphy.com/submit>`.
  6. For the first runs you could also use the public beta key you can get `here <https://github.com/giphy/GiphyAPI>`.
  7. Syntax
  8. ------
  9. {% giphy gif_id ["alt text"|'alt text'] %}
  10. Example
  11. -------
  12. {% giphy aMSJFS6oFX0fC 'ive had some free time' %}
  13. Output
  14. ------
  15. <a href="http://giphy.com/gifs/veronica-mars-aMSJFS6oFX0fC"><img src="http://media4.giphy.com/media/aMSJFS6oFX0fC/giphy.gif" alt="ive had some free time"></a>
  16. """
  17. import json
  18. import re
  19. try:
  20. from urllib.request import urlopen
  21. except ImportError:
  22. from urllib import urlopen
  23. from .mdx_liquid_tags import LiquidTags
  24. SYNTAX = '''{% giphy gif_id ["alt text"|'alt text'] %}'''
  25. GIPHY = re.compile('''(?P<gif_id>[\S+]+)(?:\s+(['"]{0,1})(?P<alt>.+)(\\2))?''')
  26. def get_gif(api_key, gif_id):
  27. '''Returns dict with gif informations from the API.'''
  28. url = 'http://api.giphy.com/v1/gifs/{}?api_key={}'.format(gif_id, api_key)
  29. r = urlopen(url)
  30. return json.loads(r.read().decode('utf-8'))
  31. def create_html(api_key, attrs):
  32. '''Returns complete html tag string.'''
  33. gif = get_gif(api_key, attrs['gif_id'])
  34. if 'alt' not in attrs.keys():
  35. attrs['alt'] = 'source: {}'.format(gif['data']['source'])
  36. html_out = '<a href="{}">'.format(gif['data']['url'])
  37. html_out += '<img src="{}" alt="{}">'.format(
  38. gif['data']['images']['original']['url'],
  39. attrs['alt'])
  40. html_out += '</a>'
  41. return html_out
  42. def main(api_key, markup):
  43. '''Doing the regex parsing and running the create_html function.'''
  44. match = GIPHY.search(markup)
  45. attrs = None
  46. if match:
  47. attrs = dict(
  48. [(key, value.strip())
  49. for (key, value) in match.groupdict().items() if value])
  50. else:
  51. raise ValueError('Error processing input. '
  52. 'Expected syntax: {}'.format(SYNTAX))
  53. return create_html(api_key, attrs)
  54. @LiquidTags.register('giphy')
  55. def giphy(preprocessor, tag, markup):
  56. api_key = preprocessor.configs.getConfig('GIPHY_API_KEY')
  57. if api_key is None:
  58. raise ValueError('Please set GIPHY_API_KEY.')
  59. return main(api_key, markup)
  60. # ---------------------------------------------------
  61. # This import allows image tag to be a Pelican plugin
  62. from liquid_tags import register