python-markdown-oembed/src/python_markdown_oembed_extension/oembedextension.py

40 lines
1.4 KiB
Python
Raw Normal View History

2012-11-13 21:28:10 +00:00
from markdown import Extension
import oembed
from python_markdown_oembed_extension.endpoints import DEFAULT_ENDPOINTS
from python_markdown_oembed_extension.inlinepatterns import OEmbedLinkPattern, OEMBED_LINK_RE
2012-11-13 21:28:10 +00:00
class OEmbedExtension(Extension):
def __init__(self, **kwargs):
self.config = {
'allowed_endpoints': [
DEFAULT_ENDPOINTS,
2026-03-02 16:25:43 +00:00
"A list of oEmbed endpoints to allow. "
"Defaults to endpoints.DEFAULT_ENDPOINTS",
],
'wrapper_class': [
'oembed',
"CSS class(es) for the <figure> wrapper element. "
"Set to empty string to disable wrapping.",
],
}
2026-03-02 16:25:43 +00:00
super().__init__(**kwargs)
2022-08-08 09:33:25 +00:00
def extendMarkdown(self, md):
2026-03-02 16:25:43 +00:00
consumer = self._prepare_oembed_consumer()
wrapper_class = self.getConfig('wrapper_class', 'oembed')
link_pattern = OEmbedLinkPattern(
OEMBED_LINK_RE, md, consumer, wrapper_class=wrapper_class,
)
# Priority 175 — run before the default image pattern (priority 150)
2022-08-16 06:19:59 +00:00
md.inlinePatterns.register(link_pattern, 'oembed_link', 175)
2012-11-13 21:28:10 +00:00
2026-03-02 16:25:43 +00:00
def _prepare_oembed_consumer(self):
allowed_endpoints = self.getConfig('allowed_endpoints', DEFAULT_ENDPOINTS)
2012-11-13 21:28:10 +00:00
consumer = oembed.OEmbedConsumer()
2026-03-02 16:25:43 +00:00
for endpoint in (allowed_endpoints or []):
consumer.addEndpoint(endpoint)
2012-11-13 21:28:10 +00:00
return consumer