2023-02-03 20:53:58 +01:00
|
|
|
from typing import Any
|
|
|
|
from xml.etree.ElementTree import Element
|
|
|
|
|
|
|
|
import markdown
|
|
|
|
from django.contrib.staticfiles.storage import staticfiles_storage
|
|
|
|
from markdown.extensions import Extension
|
2023-10-12 19:43:45 +02:00
|
|
|
from typing_extensions import override
|
2023-02-03 20:53:58 +01:00
|
|
|
|
2024-05-20 22:09:35 +02:00
|
|
|
from zerver.lib.markdown.priorities import PREPROCESSOR_PRIORITIES
|
2023-02-03 20:53:58 +01:00
|
|
|
|
|
|
|
|
|
|
|
class MarkdownStaticImagesGenerator(Extension):
|
2023-10-12 19:43:45 +02:00
|
|
|
@override
|
2023-02-03 20:53:58 +01:00
|
|
|
def extendMarkdown(self, md: markdown.Markdown) -> None:
|
|
|
|
md.treeprocessors.register(
|
|
|
|
StaticImageProcessor(md),
|
|
|
|
"static_images",
|
2024-05-20 22:09:35 +02:00
|
|
|
PREPROCESSOR_PRIORITIES["static_images"],
|
2023-02-03 20:53:58 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
class StaticImageProcessor(markdown.treeprocessors.Treeprocessor):
|
|
|
|
"""
|
|
|
|
Rewrite img tags which refer to /static/ to use staticfiles
|
|
|
|
"""
|
|
|
|
|
2023-10-12 19:43:45 +02:00
|
|
|
@override
|
2023-02-03 20:53:58 +01:00
|
|
|
def run(self, root: Element) -> None:
|
|
|
|
for img in root.iter("img"):
|
|
|
|
url = img.get("src")
|
|
|
|
if url is not None and url.startswith("/static/"):
|
2024-09-03 19:42:14 +02:00
|
|
|
img.set("src", staticfiles_storage.url(url.removeprefix("/static/")))
|
2023-02-03 20:53:58 +01:00
|
|
|
|
|
|
|
|
|
|
|
def makeExtension(*args: Any, **kwargs: str) -> MarkdownStaticImagesGenerator:
|
|
|
|
return MarkdownStaticImagesGenerator(*args, **kwargs)
|