返回 Social Auto Upload
article_content.py
根目录 / utils / article_content.py
1 """平台无关的文章正文:安全内联 HTML、正文顺序和相对于原稿的图片路径。"""
2 from __future__ import annotations
3
4 import re
5 from collections import Counter
6 from hashlib import sha256
7 from html import escape
8 from html.parser import HTMLParser
9 from pathlib import Path
10 from urllib.parse import quote, unquote, urlsplit
11
12 import tinycss2
13
14
15 ARTICLE_TAGS = {
16 "section", "div", "p", "br", "h1", "h2", "h3", "h4", "h5", "h6", "span",
17 "strong", "b", "em", "i", "u", "s", "del", "blockquote", "ol", "ul", "li",
18 "hr", "img", "a", "pre", "code", "table", "thead", "tbody", "tfoot", "tr",
19 "th", "td", "figure", "figcaption", "sup", "sub",
20 }
21 ARTICLE_FORMAT_TAGS = ARTICLE_TAGS - {"section", "div", "p", "br", "span", "img", "b", "i"}
22
23
24 def validate_article_style(style: str) -> None:
25 """保留排版声明,拒绝带外部资源或可执行内容的 CSS;不静默删除输入样式。"""
26 def inspect(tokens):
27 for token in tokens:
28 if token.type in {"error", "url", "at-keyword"}:
29 raise ValueError("正文 CSS 不能包含语法错误、外部资源或 @ 规则")
30 if token.type == "function":
31 if token.lower_name in {"url", "expression", "var"}:
32 raise ValueError(f"正文 CSS 不支持 {token.name}(),请提供已内联的具体样式值")
33 inspect(token.arguments)
34 if hasattr(token, "content"):
35 inspect(token.content)
36 for declaration in tinycss2.parse_declaration_list(style, skip_comments=True, skip_whitespace=True):
37 if declaration.type != "declaration" or declaration.lower_name.startswith(("--", "-moz-binding")):
38 raise ValueError("正文 style 必须为具体的 CSS 声明,不支持变量或规则块")
39 if declaration.lower_name in {"behavior", "-ms-behavior"}:
40 raise ValueError("正文 CSS 不能包含可执行行为")
41 inspect(declaration.value)
42
43
44 class ArticleDocument(HTMLParser):
45 """解析后保留样式及文字/图片位置;平台可对这份结果增加自己的限制。"""
46
47 VOID_TAGS = {"br", "hr", "img"}
48
49 def __init__(self, html: str, base_dir: Path):
50 super().__init__(convert_charrefs=True)
51 self.base_dir = base_dir.resolve()
52 self.parts: list[str | Path] = []
53 self.text: list[str] = []
54 self.sequence: list[str] = []
55 self.images: list[Path] = []
56 self.image_attributes: list[dict] = []
57 self.formats: Counter = Counter()
58 self.tags: Counter = Counter()
59 self.attributes: dict[str, set[str]] = {}
60 self.stack: list[str] = []
61 self.in_head = False
62 self.body_style = ""
63 self.html_style = ""
64 self.source_format = "html"
65 self.theme: str | None = None
66 self.metadata: dict = {}
67 self.feed(html)
68 self.close()
69 if self.stack:
70 raise ValueError(f"正文 HTML 标签未闭合: {self.stack[-1]}")
71 if not "".join(self.text).strip():
72 raise ValueError("图文正文不能为空,请提供正文文字")
73 image_index = 0
74 content = []
75 for part in self.parts:
76 content.append(self.image_html(image_index) if isinstance(part, Path) else part)
77 if isinstance(part, Path):
78 image_index += 1
79 self.content_html = "".join(content)
80 normalize = lambda value: re.sub(r"[\s\u200b\ufeff]+", "", value)
81 self.manifest = {
82 "text_sha256": sha256(normalize("".join(self.text)).encode()).hexdigest(),
83 "structure_sha256": sha256(normalize("".join(self.sequence)).encode()).hexdigest(),
84 "image_count": len(self.images), "formats": dict(self.formats),
85 }
86
87 def image_html(self, index: int) -> str:
88 """重建图片时保留排版属性,以绝对路径保持输出移动后的资源定位。"""
89 attrs = {**self.image_attributes[index], "src": quote(self.images[index].as_posix(), safe="/:")}
90 return "<img" + "".join(f' {key}="{escape(value or "", quote=True)}"' for key, value in attrs.items()) + ">"
91
92 def handle_starttag(self, tag, attrs):
93 attributes = dict(attrs)
94 if tag == "head":
95 self.in_head = True
96 return
97 if tag in {"script", "iframe", "object", "embed", "link", "style"}:
98 raise ValueError(f"正文不支持 <{tag}>;样式请使用元素内联 style,不引用外部资源")
99 if self.in_head:
100 return
101 if tag == "html":
102 if set(attributes) - {"lang", "style"}:
103 raise ValueError("<html> 仅支持 lang 和 style 属性")
104 self.html_style = attributes.get("style") or ""
105 if self.html_style.strip():
106 validate_article_style(self.html_style)
107 self.parts.append(f'<section style="{escape(self.html_style, quote=True)}">')
108 return
109 if tag == "body":
110 if set(attributes) - {"style", "class", "id"}:
111 raise ValueError("<body> 仅支持 style、class、id 属性")
112 self.body_style = attributes.get("style") or ""
113 if self.body_style.strip():
114 validate_article_style(self.body_style)
115 self.parts.append(f'<section style="{escape(self.body_style, quote=True)}">')
116 return
117 if tag not in ARTICLE_TAGS:
118 raise ValueError(f"正文暂不支持 <{tag}>")
119 self.attributes.setdefault(tag, set()).update(attributes)
120 allowed = {"style", "class", "id", "title"}
121 if tag == "img":
122 allowed |= {"src", "alt", "width", "height"}
123 if tag == "a":
124 allowed |= {"href"}
125 if tag in {"th", "td"}:
126 allowed |= {"colspan", "rowspan", "align"}
127 if tag == "ol":
128 allowed |= {"start"}
129 if set(attributes) - allowed - {key for key in attributes if key.startswith("data-")}:
130 raise ValueError(f"<{tag}> 不支持属性 {', '.join(sorted(set(attributes) - allowed))}")
131 if "style" in attributes:
132 validate_article_style(attributes["style"] or "")
133 if tag == "a" and "href" in attributes:
134 href = attributes["href"] or ""
135 if not href.startswith("#") and urlsplit(href).scheme not in {"http", "https", "mailto"}:
136 raise ValueError("正文链接仅支持 http/https、mailto 或文内锚点")
137 if tag == "img":
138 source = unquote(attributes.pop("src", "") or "")
139 if (not source or source.startswith("//") or
140 (not Path(source).is_absolute() and re.match(r"^[a-zA-Z][a-zA-Z0-9+.-]*:", source))):
141 raise ValueError("正文图片 src 必须为本地相对路径或绝对路径,不支持网络地址、file URL 和 data URL")
142 image = (self.base_dir / Path(source).expanduser()).resolve()
143 if not image.is_file():
144 raise FileNotFoundError(f"图片不存在: {image}")
145 self.parts.append(image)
146 self.images.append(image)
147 self.image_attributes.append(attributes)
148 self.sequence.append("\x00IMG\x00")
149 return
150 normalized = {"b": "strong", "i": "em"}.get(tag, tag)
151 self.tags[normalized] += 1
152 self.parts.append("<" + normalized + "".join(
153 f' {key}="{escape(value or "", quote=True)}"' for key, value in attributes.items()) + ">")
154 if tag == "hr":
155 self.sequence.append("\x00HR\x00")
156 if normalized in ARTICLE_FORMAT_TAGS:
157 self.formats[normalized] += 1
158 if tag not in self.VOID_TAGS:
159 self.stack.append(tag)
160
161 def handle_startendtag(self, tag, attrs):
162 self.handle_starttag(tag, attrs)
163 if tag not in self.VOID_TAGS and tag not in {"meta", "link"}:
164 self.handle_endtag(tag)
165
166 def handle_endtag(self, tag):
167 if tag == "head":
168 self.in_head = False
169 return
170 if self.in_head:
171 return
172 if tag == "html":
173 if self.html_style.strip():
174 self.parts.append("</section>")
175 return
176 if tag == "body":
177 if self.body_style.strip():
178 self.parts.append("</section>")
179 return
180 if not self.stack or self.stack.pop() != tag:
181 raise ValueError(f"正文 HTML 标签未正确闭合: </{tag}>")
182 normalized = {"b": "strong", "i": "em"}.get(tag, tag)
183 self.parts.append(f'</{normalized}>')
184
185 def handle_data(self, data):
186 if not self.in_head:
187 self.parts.append(escape(data))
188 self.text.append(data)
189 self.sequence.append(data)
190
190 lines PYTHON