python-markdown-oembed/mdx_oembed/inlinepatterns.py

41 lines
1.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?:)?//[^\)]*)' \
2022-08-16 06:18:53 +00:00
r'(?<!png)(?<!jpg)(?<!jpeg)(?<!gif)(?<!avif)(?<!webp)\)'
2012-11-13 21:28:10 +00:00
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)
if html is None:
return None
else:
2023-08-08 13:58:56 +00:00
html = f'<figure class="oembed ratio ratio-16x9">{ html }</figure>'
2022-08-16 06:18:53 +00:00
placeholder = self.md.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:
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']