python-markdown-oembed/mdx_oembed/extension.py

42 lines
1.5 KiB
Python
Raw Normal View History

from __future__ import annotations
2012-11-13 21:28:10 +00:00
from markdown import Extension
from mdx_oembed.endpoints import DEFAULT_ENDPOINTS
from mdx_oembed.inlinepatterns import OEMBED_LINK_RE, OEmbedLinkPattern
from mdx_oembed.oembed import OEmbedConsumer
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)
def extendMarkdown(self, md): # noqa: N802
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)
consumer = OEmbedConsumer()
2026-03-02 16:25:43 +00:00
for endpoint in (allowed_endpoints or []):
consumer.add_endpoint(endpoint)
2012-11-13 21:28:10 +00:00
return consumer