mirror of
https://github.com/Hopiu/python-markdown-oembed.git
synced 2026-03-16 22:10:24 +00:00
40 lines
1.1 KiB
Python
40 lines
1.1 KiB
Python
# -*- coding: utf-8 -*-
|
|
import logging
|
|
from markdown.inlinepatterns import Pattern
|
|
import oembed
|
|
|
|
|
|
LOG = logging.getLogger(__name__)
|
|
|
|
|
|
OEMBED_LINK_RE = r'\!\[([^\]]*)\]\(((?:https?:)?//[^\)]*)' \
|
|
r'(?<!png)(?<!jpg)(?<!jpeg)(?<!gif)(?<!avif)(?<!webp)\)'
|
|
|
|
|
|
class OEmbedLinkPattern(Pattern):
|
|
|
|
def __init__(self, pattern, md=None, oembed_consumer=None):
|
|
Pattern.__init__(self, pattern, md=md)
|
|
self.consumer = oembed_consumer
|
|
|
|
def handleMatch(self, match):
|
|
html = self.get_oembed_html_for_match(match)
|
|
if html is None:
|
|
return None
|
|
else:
|
|
html = "<figure class=\"oembed\">%s</figure>" % html
|
|
placeholder = self.md.htmlStash.store(html)
|
|
return placeholder
|
|
|
|
def get_oembed_html_for_match(self, match):
|
|
url = match.group(3).strip()
|
|
try:
|
|
response = self.consumer.embed(url)
|
|
except oembed.OEmbedNoEndpoint:
|
|
LOG.error("No OEmbed Endpoint")
|
|
return None
|
|
except Exception as e:
|
|
LOG.error(e)
|
|
return None
|
|
else:
|
|
return response['html']
|