feat: 添加封面图处理功能,支持从 frontmatter 解析绝对 URL,并为 RSS 项目附加封面
This commit is contained in:
+98
-11
@@ -6,9 +6,12 @@ import I18nKey from "@i18n/i18nKey";
|
||||
import { i18n } from "@i18n/translation";
|
||||
import { getSortedPosts } from "@utils/content-utils";
|
||||
import { formatDateI18nWithTime } from "@utils/date-utils";
|
||||
import { url } from "@utils/url-utils";
|
||||
import type { APIContext } from "astro";
|
||||
import { processCoverImageSync } from "@utils/image-utils";
|
||||
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 * as path from "node:path";
|
||||
import sanitizeHtml from "sanitize-html";
|
||||
import { siteConfig } from "@/config";
|
||||
import pkg from "../../package.json";
|
||||
@@ -16,44 +19,128 @@ import pkg from "../../package.json";
|
||||
function stripInvalidXmlChars(str: string): string {
|
||||
return str.replace(
|
||||
// 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, "&")}"/>`;
|
||||
if (body !== undefined) {
|
||||
item.content = `<img src="${coverUrl}" alt="" />${body}`;
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(context: APIContext) {
|
||||
const blog = await getSortedPosts();
|
||||
const renderers = await loadRenderers([getMDXRenderer()]);
|
||||
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[] = [];
|
||||
for (const post of blog) {
|
||||
const coverUrl = await resolveCoverUrl(post, siteOrigin);
|
||||
if (post.data.password) {
|
||||
feedItems.push({
|
||||
const item: RSSFeedItem = {
|
||||
title: post.data.title,
|
||||
pubDate: post.data.published,
|
||||
description: post.data.description || "",
|
||||
link: url(`/posts/${post.id}/`),
|
||||
content: i18n(I18nKey.passwordProtectedRss),
|
||||
});
|
||||
};
|
||||
if (coverUrl) {
|
||||
attachCover(item, coverUrl);
|
||||
}
|
||||
feedItems.push(item);
|
||||
continue;
|
||||
}
|
||||
const { Content } = await render(post);
|
||||
const rawContent = await container.renderToString(Content);
|
||||
const cleanedContent = stripInvalidXmlChars(rawContent);
|
||||
feedItems.push({
|
||||
const body = sanitizeHtml(cleanedContent, {
|
||||
allowedTags: sanitizeHtml.defaults.allowedTags.concat(["img"]),
|
||||
});
|
||||
const item: RSSFeedItem = {
|
||||
title: post.data.title,
|
||||
pubDate: post.data.published,
|
||||
description: post.data.description || "",
|
||||
link: url(`/posts/${post.id}/`),
|
||||
content: sanitizeHtml(cleanedContent, {
|
||||
allowedTags: sanitizeHtml.defaults.allowedTags.concat(["img"]),
|
||||
}),
|
||||
});
|
||||
content: body,
|
||||
};
|
||||
if (coverUrl) {
|
||||
attachCover(item, coverUrl, body);
|
||||
}
|
||||
feedItems.push(item);
|
||||
}
|
||||
return rss({
|
||||
title: siteConfig.title,
|
||||
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>
|
||||
<templateThemeVersion>${pkg.version}</templateThemeVersion>
|
||||
<templateThemeUrl>https://github.com/CuteLeaf/Firefly</templateThemeUrl>
|
||||
|
||||
Reference in New Issue
Block a user