python-markdown-oembed/mdx_oembed/inlinepatterns.py

37 lines
1 KiB
Python
Raw Normal View History

2012-11-13 21:28:10 +00:00
# -*- coding: utf-8 -*-
import logging
from markdown.inlinepatterns import Pattern
import oembed
2012-11-13 21:28:10 +00:00
LOG = logging.getLogger(__name__)
OEMBED_LINK_RE = r'\!\[([^\]]*)\]\(((?:https?:)?//[^\)]*)' \
2012-11-13 21:28:10 +00:00
r'(?<!png)(?<!jpg)(?<!jpeg)(?<!gif)\)'
class OEmbedLinkPattern(Pattern):
def __init__(self, pattern, markdown_instance=None, oembed_consumer=None):
Pattern.__init__(self, pattern, markdown_instance)
self.consumer = oembed_consumer
def handleMatch(self, match):
2012-11-14 18:15:41 +00:00
html = self.get_oembed_html_for_match(match)
if html is None:
return None
else:
html = "<figure class=\"oembed\">%s</figure>" % html
placeholder = self.markdown.htmlStash.store(html)
return placeholder
2012-11-14 18:15:41 +00:00
def get_oembed_html_for_match(self, match):
2012-11-13 21:28:10 +00:00
url = match.group(3).strip()
try:
response = self.consumer.embed(url)
except oembed.OEmbedNoEndpoint:
return None
2012-11-14 18:15:41 +00:00
else:
return response['html']