feat(scraping): preserve supported SVG artwork (#7463)

This commit is contained in:
jxxghp
2026-11-19 00:13:33 +08:00
committed by GitHub
parent d5ccc1210d
commit cd11bbe3bc
4 changed files with 99 additions and 6 deletions

View File

@@ -401,7 +401,8 @@ class ScrapingChain(ChainBase, ConfigReloadMixin, metaclass=Singleton):
MUSIC_LEGACY_LYRICS_EXTENSIONS = (".lyricsfile.yaml", ".txt")
# 与音频元数据读取器对同目录 CUE 的数量上限保持一致
MUSIC_MAX_CUE_FILES = 32
IMAGE_EXTENSIONS = frozenset({".jpg", ".jpeg", ".png", ".webp"})
# SVG 作为矢量原图保存,并由实际内容校验后交给媒体服务器读取。
IMAGE_EXTENSIONS = frozenset({".jpg", ".jpeg", ".png", ".webp", ".svg"})
_music_track_prefix_pattern = re.compile(
r"^\s*(?:(?:cd|disc)\s*\d+\s*[-_. ]+)?(?:\d+\s*[-_. ]+)+",
flags=re.IGNORECASE,
@@ -530,6 +531,7 @@ class ScrapingChain(ChainBase, ConfigReloadMixin, metaclass=Singleton):
首个目标上传成功后,后续目标优先尝试同存储硬链接;不支持或链接失败时,
从同一份下载临时文件复制后上传,避免重复请求远端地址。
图片格式按内容确认,受支持的 SVG 会保留矢量原图和 ``.svg`` 后缀。
:param fileitem: 首个图片目标所在的目录项
:param path: 首个图片目标路径
@@ -574,7 +576,10 @@ class ScrapingChain(ChainBase, ConfigReloadMixin, metaclass=Singleton):
else:
logger.warn(f"图片保存失败:{target_path}")
except Exception as err:
logger.error(f"{url} 图片下载失败:{str(err)}!")
if isinstance(err, ValueError) and self._normalize_image_suffix(url) == ".svg":
logger.warn(f"跳过不支持的 SVG 图片:{url} - {err}")
else:
logger.error(f"{url} 图片下载失败:{str(err)}!")
finally:
self._cleanup_temp_file(downloaded_path)
@@ -680,7 +685,7 @@ class ScrapingChain(ChainBase, ConfigReloadMixin, metaclass=Singleton):
将图片地址或文件名的扩展名归一为受支持的小写后缀。
:param value: 图片 URL 或来源文件名
:return: ``.jpg``、``.png`` 或 ``.webp`` 等归一后的后缀
:return: ``.jpg``、``.png``、``.webp`` 或 ``.svg`` 等归一后的后缀
"""
suffix = Path(urlsplit(value or "").path).suffix.lower()
if suffix == ".jpeg":

View File

@@ -2,22 +2,43 @@
媒体图片内容与落盘格式的纯转换规则。
"""
import re
from io import BytesIO
from xml.etree import ElementTree
from PIL import Image
def normalize_artwork(content: bytes) -> tuple[bytes, str]:
"""
验证图片并按实际内容选择媒体服务器通用的文件后缀。
验证图片并按实际内容选择落盘格式。
JPEG 和 PNG 保留原始字节,WebP 无损转为 PNG,以保留透明度并避免远程
URL 后缀决定本地格式。本函数只处理内存数据,不访问文件或网络。
URL 后缀决定本地格式。有效 SVG 保留原始字节和矢量格式,供支持 SVG 的
媒体服务器读取;不支持 SVG 的媒体服务器可能忽略该图片。本函数只处理内存
数据,不访问文件或网络。
:param content: 完整下载的图片字节
:return: 规范图片字节与小写后缀;JPEG 统一使用 ``.jpg``
:raises ValueError: 图片无效或格式不是 JPEG、PNG、WebP
:raises ValueError: 图片无效或格式不是 JPEG、PNG、WebP、SVG
"""
svg_probe = content.lstrip(b"\xef\xbb\xbf \t\r\n")
if svg_probe.startswith((b"<?xml", b"<!--", b"<svg")):
# SVG 不需要 DTD 或实体声明,拒绝它们以免解析不可信图片时扩展实体。
if re.search(rb"<!\s*(?:DOCTYPE|ENTITY)\b", content, flags=re.IGNORECASE):
raise ValueError("不支持包含文档类型或实体声明的 SVG 图片")
try:
root = ElementTree.fromstring(content)
except ElementTree.ParseError:
pass
else:
namespace, separator, local_name = root.tag.rpartition("}")
if (
local_name == "svg"
and (not separator or namespace == "{http://www.w3.org/2000/svg")
):
return content, ".svg"
try:
with Image.open(BytesIO(content)) as image:
image_format = image.format

View File

@@ -40,6 +40,37 @@ def test_webp_conversion_preserves_transparency() -> None:
assert image.convert("RGBA").getpixel((0, 0))[3] == 0
def test_normalize_artwork_preserves_valid_svg() -> None:
"""
有效 SVG 保留来源字节,供支持 SVG 的媒体服务器读取矢量图。
"""
source = (
b'<?xml version="1.0" encoding="UTF-8"?>'
b'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1">'
b"<path d=\"M0 0h1v1z\"/></svg>"
)
normalized, suffix = normalize_artwork(source)
assert normalized == source
assert suffix == ".svg"
@pytest.mark.parametrize(
"content",
[
b'<!DOCTYPE svg [<!ENTITY x "expanded">]><svg>&x;</svg>',
b'<svg xmlns="urn:not-svg"/>',
],
)
def test_normalize_artwork_rejects_unsupported_svg_xml(content: bytes) -> None:
"""
拒绝带实体声明或伪造 SVG 命名空间的 XML 内容。
"""
with pytest.raises(ValueError):
normalize_artwork(content)
@pytest.mark.parametrize("content", [b"", b"<html>not artwork</html>", b"RIFF0000WEBPbroken"])
def test_normalize_artwork_rejects_invalid_content(content) -> None:
"""

View File

@@ -855,6 +855,42 @@ def test_download_and_save_image_reuses_one_download(
assert all(not path.exists() for path in uploaded_paths)
@patch("app.chain.scraping._scraping_http_snapshot")
def test_download_and_save_image_preserves_svg_suffix_and_bytes(
mock_http, image_context, tmp_path,
) -> None:
"""
SVG logo 下载后使用实际格式后缀落盘,并保留矢量原始字节。
"""
chain = image_context.media_chain
chain._download_and_save_image = image_context.original_download
fileitem = FileItem(path=str(tmp_path), name=tmp_path.name, type="dir", storage="local")
content = b'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 1"/>'
stream = mock_http.return_value.stream.return_value.__enter__.return_value
stream.status_code = 200
stream.iter_content.return_value = [content]
def upload(*, fileitem, path, new_name):
"""
将上传临时文件写到测试目标,并模拟存储适配器消费临时文件。
"""
destination = Path(fileitem.path) / new_name
destination.write_bytes(path.read_bytes())
path.unlink()
return FileItem(path=str(destination), name=new_name, type="file", storage="local")
chain.storagechain.upload_file.side_effect = upload
chain._download_and_save_image(
fileitem,
tmp_path / "logo.jpg",
"https://artwork.invalid/logo.svg",
)
saved_logo = tmp_path / "logo.svg"
assert saved_logo.read_bytes() == content
chain.storagechain.upload_file.assert_called_once()
@patch("app.chain.scraping._scraping_http_snapshot")
def test_image_download_failure_cleans_temp_files(mock_http, image_context, tmp_path) -> None:
"""