From 6f8fff461bebc1b53d0019e1aac7794e3b16c933 Mon Sep 17 00:00:00 2001 From: BlackCyan Date: Sun, 4 Oct 2026 18:54:31 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E5=B0=81=E9=9D=A2?= =?UTF-8?q?=E5=9B=BE=E5=A4=84=E7=90=86=E5=8A=9F=E8=83=BD=EF=BC=8C=E6=94=AF?= =?UTF-8?q?=E6=8C=81=E4=BB=8E=20frontmatter=20=E8=A7=A3=E6=9E=90=E7=BB=9D?= =?UTF-8?q?=E5=AF=B9=20URL=EF=BC=8C=E5=B9=B6=E4=B8=BA=20RSS=20=E9=A1=B9?= =?UTF-8?q?=E7=9B=AE=E9=99=84=E5=8A=A0=E5=B0=81=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/pages/rss.xml.ts | 109 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 98 insertions(+), 11 deletions(-) diff --git a/src/pages/rss.xml.ts b/src/pages/rss.xml.ts index d870197..2ffd441 100644 --- a/src/pages/rss.xml.ts +++ b/src/pages/rss.xml.ts @@ -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( + "../**/*.{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 { + 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 = ``; + if (body !== undefined) { + item.content = `${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: `Firefly ${pkg.version} https://github.com/CuteLeaf/Firefly