python-markdown-oembed/mdx_oembed/inlinepatterns.py

43 lines
1.2 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):
2022-08-15 14:41:35 +00:00
def __init__(self, pattern, md=None, oembed_consumer=None):
Pattern.__init__(self, pattern, md=md)
2012-11-13 21:28:10 +00:00
self.consumer = oembed_consumer
def handleMatch(self, match):
2012-11-14 18:15:41 +00:00
html = self.get_oembed_html_for_match(match)
2022-08-15 15:18:39 +00:00
LOG.warn(html)
2012-11-14 18:15:41 +00:00
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()
2022-08-15 15:18:39 +00:00
LOG.warn(url)
try:
response = self.consumer.embed(url)
except oembed.OEmbedNoEndpoint:
2022-08-15 14:21:34 +00:00
LOG.error("No OEmbed Endpoint")
return None
2020-04-07 12:37:38 +00:00
except Exception as e:
2022-08-15 14:21:34 +00:00
LOG.error(e)
2020-04-07 12:37:38 +00:00
return None
2012-11-14 18:15:41 +00:00
else:
return response['html']