This commit is contained in:
2026-04-17 06:16:30 +09:00
parent 1a2410488f
commit dc7472de89
20 changed files with 254 additions and 45 deletions
+58
View File
@@ -1,6 +1,8 @@
import io
import json
import yaml
import random
import mistune
from pathlib import Path
from bs4 import BeautifulSoup
from markitdown import MarkItDown
@@ -22,6 +24,11 @@ templates.env.globals["get_access_count"] = accesscounter.get
templates.env.globals["server_version"] = server_version
templates.env.globals["onion_site_url"] = f"http://{onion_hostname}/"
class CustomHTMLRenderer(mistune.HTMLRenderer):
def block_code(self, code, **attrs):
return f'<pre>{mistune.escape(code)}</pre>\n'
htmlitdown = mistune.create_markdown(renderer=CustomHTMLRenderer(escape=False))
def get_daily_quote() -> str:
seed = str(datetime.now(timezone.utc).date())
with Path.cwd().joinpath("public", "quotes.txt").open("r") as f:
@@ -104,6 +111,8 @@ async def default_response(request: Request, full_path: str) -> Response:
markdown_mode = False
if "curl" in request.headers.get("user-agent", "").lower():
markdown_mode = True
original_path = full_path
if full_path.endswith(".md"):
markdown_mode = True
full_path = full_path[:-3] + ".html"
@@ -151,6 +160,55 @@ async def default_response(request: Request, full_path: str) -> Response:
except TemplateNotFound:
continue
if original_path in ["", "/"]:
markdown_candidates = ["index.md"]
elif original_path.endswith(".md"):
markdown_candidates = [original_path.lstrip('/')]
else:
markdown_candidates = [f"{original_path.strip('/')}.md", f"{original_path.strip('/')}/index.md"]
for name in markdown_candidates:
try:
markdown_path = Path.cwd().joinpath("public", name)
if not markdown_path.is_relative_to(Path.cwd().joinpath("public")):
continue
with markdown_path.open("r") as f:
markdown = f.read()
if markdown_mode:
response = PlainTextResponse(markdown, status_code=200, media_type="text/markdown")
else:
if not markdown.startswith("---"):
front = {}
body = markdown
else:
end = markdown.find("\n---", 3)
if end == -1:
front = {}
body = markdown
else:
front = yaml.safe_load(markdown[3:end]) or {}
body = markdown[end+4:].lstrip("\n")
html = htmlitdown(body)
source = f'{{% extends "{"/base-light.html" if lightweight_mode else "/base.html"}" %}}\n'
for block in front:
source += f'{{% block {block} %}}{front[block]}{{% endblock %}}\n'
source += f'{{% block content %}}\n{html}\n{{% endblock %}}\n'
content = templates.env.from_string(source).render(request=request)
response = Response(content=content, status_code=200, media_type="text/html")
if lightweight_mode:
response.set_cookie("lightweight_mode", "true", samesite="lax")
elif request.cookies.get("lightweight_mode", "") == "true":
response.set_cookie("lightweight_mode", "false", samesite="lax")
accesscounter.increase()
return response
except FileNotFoundError:
continue
try:
path = Path.cwd().joinpath("public", "shorturls.json")
if not path.exists():