feat: add RSS feed generation and content management features

This commit is contained in:
radishzzz 2025-01-14 09:10:12 +00:00
parent 4d989e0a7d
commit 5d3a3b0321
6 changed files with 189 additions and 49 deletions

View file

@ -0,0 +1,20 @@
---
import themeConfig from '@/config'
const { title, subtitle, favicon } = themeConfig.site
---
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/svg+xml" href={favicon} />
<meta name="generator" content={Astro.generator} />
<title>{title} - {subtitle}</title>
<link
rel="alternate"
type="application/rss+xml"
title={title}
href={`${themeConfig.site.url}/rss.xml`}
/>
</head>

View file

@ -73,7 +73,7 @@ export const themeConfig: ThemeConfig = {
footer: {
linkA: {
name: 'RSS',
url: '#',
url: '/rss.xml',
},
linkB: {
name: 'Contact',

View file

@ -1,20 +1,10 @@
---
import Header from '@/components/Header.astro'
---
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="generator" content={Astro.generator} />
<title>Astro Basics</title>
<link
rel="alternate"
type="application/rss+xml"
title={themeConfig.site.title}
href={new URL('rss.xml', themeConfig.site.url)}
/>
</head>
<Header />
<body>
<slot />
</body>

View file

@ -1,33 +1,62 @@
import type { APIContext } from 'astro'
import type { CollectionEntry } from 'astro:content'
import themeConfig from '@/config'
import rss from '@astrojs/rss'
import { getCollection } from 'astro:content'
import MarkdownIt from 'markdown-it'
import sanitizeHtml from 'sanitize-html'
import
const parser = new MarkdownIt()
const { title, description, url } = themeConfig.site
const { language } = themeConfig.global
const followConfig = themeConfig.seo?.follow
// Extract first 100 chars from content as description
function getExcerpt(content: string): string {
const plainText = sanitizeHtml(
parser.render(content),
{
allowedTags: [],
allowedAttributes: {},
},
)
return `${plainText.slice(0, 100).trim()}...`
}
// Generate RSS feed
export async function GET(_context: APIContext) {
const posts = await getCollection('blog', ({ data }) => {
return !data.draft // 只包含非草稿文章
})
const posts = await getCollection(
'posts',
({ data }: { data: CollectionEntry<'posts'>['data'] }) => !data.draft,
)
return rss({
title,
description,
site: url,
items: posts.map(post => ({
stylesheet: '/rss/styles.xsl',
items: posts.map((post: CollectionEntry<'posts'>) => ({
title: post.data.title,
pubDate: post.data.published, // 使用 published 而不是 pubDate
description: post.data.description,
pubDate: post.data.published,
description: post.data.description || getExcerpt(post.body),
link: `/posts/${post.slug}/`,
content: sanitizeHtml(parser.render(post.body), {
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img']),
}),
content: sanitizeHtml(
parser.render(post.body),
{
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img']),
},
),
})),
customData: `<language>${language}</language>`,
customData: `
<language>${language}</language>
${followConfig?.feedID && followConfig?.userID
? `<follow_challenge>
<feedId>${followConfig.feedID}</feedId>
<userId>${followConfig.userID}</userId>
</follow_challenge>`
: ''
}
`.trim(),
})
}

View file

@ -1,50 +1,91 @@
import type { CollectionEntry } from 'astro:content'
import { getCollection } from 'astro:content'
import MarkdownIt from 'markdown-it'
import sanitizeHtml, { type Tag } from 'sanitize-html'
export type Post = CollectionEntry<'posts'>
export type PostData = Post['data']
export type PostsGroupByYear = Map<number, Post[]>
export async function getPosts(isArchivePage = false) {
const posts = await getCollection('posts', ({ data }) => {
return import.meta.env.DEV || !data.draft
})
// Get all posts and sort by publish date
export async function getPosts() {
const posts = await getCollection(
'posts',
({ data }: Post) => import.meta.env.DEV || !data.draft,
)
// 按发布日期降序排序
return posts.sort((a, b) => b.data.published.valueOf() - a.data.published.valueOf())
return posts.sort((a: Post, b: Post) =>
b.data.published.valueOf() - a.data.published.valueOf(),
)
}
// 获取所有标签及其对应的文章
export async function getPostsByTags() {
// Group posts by tags
export async function sortPostsByTags() {
const posts = await getPosts()
const tagMap = new Map<string, Post[]>()
posts.forEach((post) => {
post.data.tags?.forEach((tag) => {
if (!tagMap.has(tag)) {
tagMap.set(tag, [])
}
tagMap.get(tag)?.push(post)
})
posts.forEach((post: Post) => {
if (post.data.tags && post.data.tags.length > 0) {
post.data.tags.forEach((tag: string) => {
if (!tagMap.has(tag)) {
tagMap.set(tag, [])
}
tagMap.get(tag)?.push(post)
})
}
})
return tagMap
}
// 获取指定标签的所有文章
// Get posts by specific tag
export async function getPostsByTag(tag: string) {
const posts = await getPosts()
return posts.filter(post => post.data.tags?.includes(tag))
return posts.filter((post: Post) =>
post.data.tags?.includes(tag),
)
}
// 获取所有标签列表
// Get all tags list
export async function getAllTags() {
const posts = await getPosts()
const tags = new Set<string>()
posts.forEach((post) => {
post.data.tags?.forEach(tag => tags.add(tag))
posts.forEach((post: Post) => {
post.data.tags?.forEach((tag: string) =>
tags.add(tag),
)
})
return Array.from(tags)
}
// Group posts by year and sort
export async function getPostsByYear(): Promise<PostsGroupByYear> {
const posts = await getPosts()
const yearMap = new Map<number, Post[]>()
// Group by year
posts.forEach((post: Post) => {
const year = post.data.published.getFullYear()
if (!yearMap.has(year)) {
yearMap.set(year, [])
}
yearMap.get(year)?.push(post)
})
// Sort posts within each year
yearMap.forEach((yearPosts) => {
yearPosts.sort((a: Post, b: Post) => {
const aDate = a.data.published
const bDate = b.data.published
const monthDiff = bDate.getMonth() - aDate.getMonth()
if (monthDiff !== 0) {
return monthDiff
}
return bDate.getDate() - aDate.getDate()
})
})
return new Map([...yearMap.entries()].sort((a, b) => b[0] - a[0]))
}