2012-11-13 21:28:10 +00:00
|
|
|
from markdown import Extension
|
|
|
|
|
import oembed
|
2023-11-06 17:58:32 +00:00
|
|
|
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):
|
|
|
|
|
|
2015-04-02 07:47:33 +00:00
|
|
|
def __init__(self, **kwargs):
|
|
|
|
|
self.config = {
|
|
|
|
|
'allowed_endpoints': [
|
2015-04-21 09:18:42 +00:00
|
|
|
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.",
|
2015-04-02 07:47:33 +00:00
|
|
|
],
|
|
|
|
|
}
|
2026-03-02 16:25:43 +00:00
|
|
|
super().__init__(**kwargs)
|
2012-11-13 23:28:04 +00:00
|
|
|
|
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):
|
2015-04-21 09:18:42 +00:00
|
|
|
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
|
2023-11-06 17:58:32 +00:00
|
|
|
|