gram.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. """
  2. Instagram Image Tag
  3. -------------------
  4. By `Tom Spalding <https://github.com/digitalvapor>`_
  5. You can see a working example at `antivapor.net/instagram-tag.html <http://antivapor.net/instagram-tag.html>`_.
  6. Based on `Liquid Image Tag <https://github.com/getpelican/pelican-plugins/blob/master/liquid_tags/img.py>`_ by `Jake Vanderplas <https://github.com/jakevdp>`_.
  7. Optional Todo:
  8. * Query JSON to automatically include descriptions.
  9. http://api.instagram.com/oembed?url=http://instagr.am/p/olw8jXiz1_/
  10. and option to add wrapping anchor link to original http://instagram.com/p/olw8jXiz1_
  11. * Default to size m
  12. http://instagr.am/p/olw8jXiz1_/media/?size=t
  13. http://instagr.am/p/olw8jXiz1_/media
  14. * Provide examples using with [Better Figures and Images](https://github.com/getpelican/pelican-plugins/tree/master/better_figures_and_images).
  15. Syntax
  16. ------
  17. {% gram shortcode [size] [width] [class name(s)] [title text | "title text" ["alt text"]] %}
  18. where size is t, m, or l, and it defaults to m. see http://instagram.com/developer/embedding.
  19. Examples
  20. --------
  21. {% gram pFG7naIZkr t %}
  22. {% gram pFJE11IZnx %}
  23. {% gram pFI0CAIZna l 400 figure 'pretty turkey tail fungus' %}
  24. {% gram rOru21oZpe l 450 test_class instagram 'warehouse window title' 'alt text' %}
  25. Output
  26. ------
  27. <img src="http://photos-c.ak.instagram.com/hphotos-ak-xaf1/t51.2885-15/917172_604907902963826_254280879_n.jpg" width="450" title="warehouse window title" alt="alt text" class="test_class instagram">
  28. """
  29. import re
  30. try:
  31. from urllib.request import urlopen
  32. except ImportError:
  33. from urllib import urlopen
  34. from .mdx_liquid_tags import LiquidTags
  35. SYNTAX = '{% gram shortcode [size] [width] [class name(s)] [title text | "title text" ["alt text"]] %}'
  36. # Regular expression for full syntax
  37. # ReGram = re.compile("""(?P<shortcode>\S+)(?:\s+(?P<size>[tml]?))?(?:\s+(?P<width>\d*))?(?:\s+(?P<class>\S*))?(?P<title>\s+.+)?""")
  38. ReGram = re.compile("""(?P<shortcode>\S+)(?:\s+(?P<size>[tml]?))?(?:\s+(?P<width>\d*))?(?:\s+(?P<class>[^']*))?(?P<title>.+)?""")
  39. # Regular expression to split the title and alt text
  40. ReTitleAlt = re.compile("""(?:"|')(?P<title>[^"']+)?(?:"|')\s+(?:"|')(?P<alt>[^"']+)?(?:"|')""")
  41. @LiquidTags.register('gram')
  42. def gram(preprocessor, tag, markup):
  43. attrs = None
  44. # Parse the markup string
  45. match = ReGram.search(markup)
  46. if match:
  47. attrs = dict([(key, val.strip())
  48. for (key, val) in match.groupdict().items() if val])
  49. else:
  50. raise ValueError('Error processing input. '
  51. 'Expected syntax: {0}'.format(SYNTAX))
  52. # Construct URI
  53. #print(attrs)
  54. shortcode = attrs['shortcode']
  55. url = 'http://instagr.am/p/'+shortcode+'/media/'
  56. del attrs['shortcode']
  57. if 'size' in attrs:
  58. size = '?size={0}'.format(attrs['size'])
  59. url = url+size
  60. del attrs['size']
  61. r = urlopen(url)
  62. if(r.getcode()==404):
  63. raise ValueError('%s isnt a photo.'%shortcode)
  64. gram_url = r.geturl()
  65. # Check if alt text is present -- if so, split it from title
  66. if 'title' in attrs:
  67. match = ReTitleAlt.search(attrs['title'])
  68. if match:
  69. attrs.update(match.groupdict())
  70. if not attrs.get('alt'):
  71. attrs['alt'] = attrs['title']
  72. #print('updated dict: '+repr(attrs))
  73. # Return the formatted text
  74. return '<img src="{0}"{1}>'.format(gram_url,' '.join(' {0}="{1}"'.format(key,val) for (key,val) in attrs.items()))
  75. #----------------------------------------------------------------------
  76. # This import allows image tag to be a Pelican plugin
  77. from liquid_tags import register