feat: 添加封面图处理功能,支持从 frontmatter 解析绝对 URL,并为 RSS 项目附加封面

This commit is contained in:
2026-10-04 18:54:31 +08:00
parent a6f77e77d3
commit 6f8fff461b
+98 -11
View File
@@ -6,9 +6,12 @@ import I18nKey from "@i18n/i18nKey";
import { i18n } from "@i18n/translation"; import { i18n } from "@i18n/translation";
import { getSortedPosts } from "@utils/content-utils"; import { getSortedPosts } from "@utils/content-utils";
import { formatDateI18nWithTime } from "@utils/date-utils"; import { formatDateI18nWithTime } from "@utils/date-utils";
import { url } from "@utils/url-utils"; import { processCoverImageSync } from "@utils/image-utils";
import type { APIContext } from "astro"; import { getFileDirFromPath, url } from "@utils/url-utils";
import type { APIContext, ImageMetadata } from "astro";
import type { CollectionEntry } from "astro:content";
import { experimental_AstroContainer as AstroContainer } from "astro/container"; import { experimental_AstroContainer as AstroContainer } from "astro/container";
import * as path from "node:path";
import sanitizeHtml from "sanitize-html"; import sanitizeHtml from "sanitize-html";
import { siteConfig } from "@/config"; import { siteConfig } from "@/config";
import pkg from "../../package.json"; import pkg from "../../package.json";
@@ -16,44 +19,128 @@ import pkg from "../../package.json";
function stripInvalidXmlChars(str: string): string { function stripInvalidXmlChars(str: string): string {
return str.replace( return str.replace(
// biome-ignore lint/suspicious/noControlCharactersInRegex: https://www.w3.org/TR/xml/#charsets // biome-ignore lint/suspicious/noControlCharactersInRegex: https://www.w3.org/TR/xml/#charsets
/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\uFDD0-\uFDEF\uFFFE\uFFFF]/g, /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F﷐-﷯￾￿]/g,
"", "",
); );
} }
// 本地封面图:import.meta.glob 让 Vite 将资源纳入构建产物(dist/_astro/...)
const coverFiles = import.meta.glob<ImageMetadata>(
"../**/*.{png,jpg,jpeg,webp,avif,gif,svg}",
{ import: "default" },
);
function getImageMime(imageUrl: string): string {
const ext = imageUrl.split(/[?#]/)[0].split(".").pop()?.toLowerCase();
switch (ext) {
case "avif":
return "image/avif";
case "webp":
return "image/webp";
case "png":
return "image/png";
case "gif":
return "image/gif";
case "svg":
return "image/svg+xml";
default:
// 随机封面 API 通常无扩展名,默认按 jpeg 处理
return "image/jpeg";
}
}
/**
* 将 frontmatter 的 image 字段解析为绝对 URL,供 RSS 阅读器显示封面。
* 支持:本地相对路径、"/" 开头的 public 路径、http(s) 远程图、"api" 随机封面。
*/
async function resolveCoverUrl(
post: CollectionEntry<"posts">,
siteOrigin: string,
): Promise<string> {
const raw = processCoverImageSync(post.data.image, post.id);
if (!raw || raw.startsWith("data:")) {
return "";
}
if (
raw.startsWith("http://") ||
raw.startsWith("https://") ||
raw.startsWith("//")
) {
return raw;
}
if (raw.startsWith("/")) {
return new URL(raw, siteOrigin).href;
}
// 本地相对路径:相对于文章所在目录
const basePath = getFileDirFromPath(post.filePath ?? "");
const normalizedPath = path
.normalize(path.join("../", basePath, raw))
.replace(/\\/g, "/");
const file = coverFiles[normalizedPath];
if (!file) {
return "";
}
const img = await file();
return new URL(img.src, siteOrigin).href;
}
// 为 item 添加封面:enclosure(标准 RSS)、media:thumbnail(MRSS),
// 并将封面作为正文第一张图(Feedly、Inoreader 等按首图提取封面的阅读器)
function attachCover(item: RSSFeedItem, coverUrl: string, body?: string): void {
item.enclosure = { url: coverUrl, length: 0, type: getImageMime(coverUrl) };
item.customData = `<media:thumbnail url="${coverUrl.replace(/&/g, "&amp;")}"/>`;
if (body !== undefined) {
item.content = `<img src="${coverUrl}" alt="" />${body}`;
}
}
export async function GET(context: APIContext) { export async function GET(context: APIContext) {
const blog = await getSortedPosts(); const blog = await getSortedPosts();
const renderers = await loadRenderers([getMDXRenderer()]); const renderers = await loadRenderers([getMDXRenderer()]);
const container = await AstroContainer.create({ renderers }); const container = await AstroContainer.create({ renderers });
// dev 下 context.url.origin 为当前开发服务器地址;静态构建时由配置的 site 决定
const siteOrigin =
context.url?.origin || context.site || "https://firefly.cuteleaf.cn";
const feedItems: RSSFeedItem[] = []; const feedItems: RSSFeedItem[] = [];
for (const post of blog) { for (const post of blog) {
const coverUrl = await resolveCoverUrl(post, siteOrigin);
if (post.data.password) { if (post.data.password) {
feedItems.push({ const item: RSSFeedItem = {
title: post.data.title, title: post.data.title,
pubDate: post.data.published, pubDate: post.data.published,
description: post.data.description || "", description: post.data.description || "",
link: url(`/posts/${post.id}/`), link: url(`/posts/${post.id}/`),
content: i18n(I18nKey.passwordProtectedRss), content: i18n(I18nKey.passwordProtectedRss),
}); };
if (coverUrl) {
attachCover(item, coverUrl);
}
feedItems.push(item);
continue; continue;
} }
const { Content } = await render(post); const { Content } = await render(post);
const rawContent = await container.renderToString(Content); const rawContent = await container.renderToString(Content);
const cleanedContent = stripInvalidXmlChars(rawContent); const cleanedContent = stripInvalidXmlChars(rawContent);
feedItems.push({ const body = sanitizeHtml(cleanedContent, {
allowedTags: sanitizeHtml.defaults.allowedTags.concat(["img"]),
});
const item: RSSFeedItem = {
title: post.data.title, title: post.data.title,
pubDate: post.data.published, pubDate: post.data.published,
description: post.data.description || "", description: post.data.description || "",
link: url(`/posts/${post.id}/`), link: url(`/posts/${post.id}/`),
content: sanitizeHtml(cleanedContent, { content: body,
allowedTags: sanitizeHtml.defaults.allowedTags.concat(["img"]), };
}), if (coverUrl) {
}); attachCover(item, coverUrl, body);
}
feedItems.push(item);
} }
return rss({ return rss({
title: siteConfig.title, title: siteConfig.title,
description: siteConfig.subtitle || "No description", description: siteConfig.subtitle || "No description",
site: context.site ?? "https://firefly.cuteleaf.cn", site: siteOrigin,
xmlns: { media: "http://search.yahoo.com/mrss/" },
customData: `<templateTheme>Firefly</templateTheme> customData: `<templateTheme>Firefly</templateTheme>
<templateThemeVersion>${pkg.version}</templateThemeVersion> <templateThemeVersion>${pkg.version}</templateThemeVersion>
<templateThemeUrl>https://github.com/CuteLeaf/Firefly</templateThemeUrl> <templateThemeUrl>https://github.com/CuteLeaf/Firefly</templateThemeUrl>