87 lines
2.1 KiB
Python
87 lines
2.1 KiB
Python
|
|
import re
|
|||
|
|
import logging
|
|||
|
|
|
|||
|
|
logger = logging.getLogger(__name__)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _strip_strikethrough(text: str) -> str:
|
|||
|
|
return re.sub(r"~~(.+?)~~", r"\1", text)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _convert_links(text: str) -> str:
|
|||
|
|
def replacer(m):
|
|||
|
|
link_text = m.group(1)
|
|||
|
|
url = m.group(2)
|
|||
|
|
return f"{link_text} ( {url} )"
|
|||
|
|
|
|||
|
|
return re.sub(r"\[([^\]]+)\]\(([^)]+)\)", replacer, text)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _strip_headings(text: str) -> str:
|
|||
|
|
def replacer(m):
|
|||
|
|
level = len(m.group(1))
|
|||
|
|
heading_text = m.group(2).strip()
|
|||
|
|
if level <= 1:
|
|||
|
|
return f"*{heading_text}*"
|
|||
|
|
return heading_text
|
|||
|
|
|
|||
|
|
return re.sub(r"^(#{1,6})\s+(.+)$", replacer, text, flags=re.MULTILINE)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def _strip_table_syntax(text: str) -> str:
|
|||
|
|
lines = text.split("\n")
|
|||
|
|
result = []
|
|||
|
|
|
|||
|
|
for line in lines:
|
|||
|
|
stripped = line.strip()
|
|||
|
|
if stripped.startswith("|") and stripped.endswith("|"):
|
|||
|
|
if "---" in stripped and "|" in stripped:
|
|||
|
|
continue
|
|||
|
|
cells = [c.strip() for c in stripped.split("|")[1:-1]]
|
|||
|
|
result.append(" ".join(cells))
|
|||
|
|
else:
|
|||
|
|
result.append(line)
|
|||
|
|
|
|||
|
|
return "\n".join(result)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def clean_for_zoom(text: str) -> str:
|
|||
|
|
if not text:
|
|||
|
|
return ""
|
|||
|
|
|
|||
|
|
text = _strip_strikethrough(text)
|
|||
|
|
text = _convert_links(text)
|
|||
|
|
text = _strip_headings(text)
|
|||
|
|
text = _strip_table_syntax(text)
|
|||
|
|
|
|||
|
|
return text.strip()
|
|||
|
|
|
|||
|
|
|
|||
|
|
def markdown_to_zoom(md_text: str) -> str:
|
|||
|
|
return clean_for_zoom(md_text)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def sanitize_text(text: str) -> str:
|
|||
|
|
"""
|
|||
|
|
清理文本以适配 Zoom Chat 的 Markdown 限制。
|
|||
|
|
|
|||
|
|
去除 Zoom 不支持的 Markdown 语法:
|
|||
|
|
- 删除线 (~~text~~) → text
|
|||
|
|
- 链接 ([text](url)) → text ( url )
|
|||
|
|
- 标题 (# title) → *title* (一级) 或 title (其余)
|
|||
|
|
- 表格 → 空格分隔的纯文本
|
|||
|
|
|
|||
|
|
Args:
|
|||
|
|
text: 原始 Markdown 文本
|
|||
|
|
|
|||
|
|
Returns:
|
|||
|
|
清理后的纯文本
|
|||
|
|
"""
|
|||
|
|
return clean_for_zoom(text)
|
|||
|
|
|
|||
|
|
|
|||
|
|
def native_to_markdown(native_content: dict | str) -> str:
|
|||
|
|
if isinstance(native_content, dict):
|
|||
|
|
return native_content.get("content", native_content.get("text", ""))
|
|||
|
|
return str(native_content)
|