BLOG-117 Auto generate sitemap and rss file (#303)
Frontend CI / build (push) Successful in 12m2s

## Description

This PR generates sitemap.xml and feed.xml from the frontend instead of the manual/toolbox script, so
the public URL scheme lives in one place and the documents are never hand-mutated.

- New SvelteKit server routes /sitemap.xml and /feed.xml, generated on demand with a short
  Cache-Control (public, max-age=300). There is no server-side cache, so the app regenerates on a
  cache miss; browsers, crawlers and any intermediary honour the header.
- A shared PostPage entity and ListPostPagesUseCase map published posts to their public URLs using
  resolve(), so the frontend route table stays the single source of truth.
- sitemap.xml (sitemap package) lists every published post plus the static pages only the frontend
  knows about: home, post list, and the terms documents.
- feed.xml (feed package) contains only posts, capped at the 20 most recent. Static pages never
  appear in the feed.
- The backend now exposes, per post, the preview image mime type and size (for a valid RSS enclosure)
  and the post updated_time. The frontend uses updated_time as sitemap lastmod, while the feed pubDate
  remains the published time.

## Package Changes

| Package | Action | Version |
| --- | --- | --- |
| feed | Added | 6.0.0 |
| sitemap | Added | 9.0.1 |
| sanitize-html | Updated | 2.17.3 -> 2.17.7 |

No Cargo.toml changes.

## Screenshots

N/A (XML endpoints).

## Reference

Resolves #117

## Checklist

- [x] A milestone is set
- [x] The related issues has been linked to this branch

---
Generated by Zed coding agent with Deepseek Flash

Reviewed-on: #303
Co-authored-by: SquidSpirit <squid@squidspirit.com>
This commit was merged in pull request #303.
This commit is contained in:
squid authored and Gitea Server committed 2026-09-23 22:39:42 +08:00
1 parent 4dde993368
commit 573d0265f8
91 files changed
+893 -868

No files matched your search

+12 -1
View File
@@ -13,7 +13,18 @@ body:
id: package
attributes:
label: Package Changes
description: List the packages changed in this PR
description: |
Dependency changes only (npm packages from package.json, Rust crates from Cargo.toml),
listed as a table using the actions Added, Removed or Updated. Write "None" if there are none.
For example:
| Package | Action | Version |
| --- | --- | --- |
| svelte-adapter-bun | Added | 1.0.1 |
| svelte | Updated | 5.55.1 -> 5.55.5 |
| eslint-plugin-import | Removed | 2.32.0 |
placeholder: |
| Package | Action | Version |
| --- | --- | --- |
- type: textarea
id: screenshots
-13
View File
@@ -51,16 +51,3 @@ jobs:
tags: |
${{ vars.REGISTRY }}/${{ vars.IMAGE_REPO_BACKEND }}:latest
${{ vars.REGISTRY }}/${{ vars.IMAGE_REPO_BACKEND }}:${{ gitea.event.release.tag_name }}
- name: Build and push (Toolbox)
uses: docker/build-push-action@v6
with:
push: true
provenance: false
context: ./script/toolbox
file: ./script/toolbox/Containerfile
cache-from: type=registry,ref=${{ vars.REGISTRY }}/${{ vars.IMAGE_REPO_TOOLBOX }}:buildcache
cache-to: type=registry,ref=${{ vars.REGISTRY }}/${{ vars.IMAGE_REPO_TOOLBOX }}:buildcache,mode=max
tags: |
${{ vars.REGISTRY }}/${{ vars.IMAGE_REPO_TOOLBOX }}:latest
${{ vars.REGISTRY }}/${{ vars.IMAGE_REPO_TOOLBOX }}:${{ gitea.event.release.tag_name }}
-6
View File
@@ -1,6 +0,0 @@
{
"typescript.preferences.importModuleSpecifier": "non-relative",
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
}
@@ -0,0 +1,19 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE post\n SET\n title = $1,\n description = $2,\n preview_image_url = $3,\n content = $4,\n published_time = $5\n WHERE id = $6\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Text",
"Text",
"Text",
"Timestamp",
"Int4"
]
},
"nullable": []
},
"hash": "9d6007d79045478eb093d928671fdb947c92c685bd0bc1526214eeb02f22553b"
}
@@ -1,19 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "\n UPDATE post\n SET \n title = $1, \n description = $2, \n preview_image_url = $3, \n content = $4, \n published_time = $5\n WHERE id = $6\n ",
"describe": {
"columns": [],
"parameters": {
"Left": [
"Text",
"Text",
"Text",
"Text",
"Timestamp",
"Int4"
]
},
"nullable": []
},
"hash": "d0867ba2857fedcdc9a754d0394c4f040d559118d0b9f8b6f4dcd6e6fde5d381"
}
@@ -65,7 +65,7 @@ impl AuthController for AuthControllerImpl {
.execute(&query.code, &query.state, expected_state, expected_nonce)
.await;
result.map(|user| UserResponseDto::from(user))
result.map(UserResponseDto::from)
}
async fn get_user(&self, user_id: i32) -> Result<UserResponseDto, AuthError> {
@@ -8,14 +8,14 @@ pub struct UserMapper {
pub email: String,
}
impl Into<User> for UserMapper {
fn into(self) -> User {
impl From<UserMapper> for User {
fn from(val: UserMapper) -> Self {
User {
id: self.id,
issuer: self.issuer,
source_id: self.source_id,
displayed_name: self.displayed_name,
email: self.email,
id: val.id,
issuer: val.issuer,
source_id: val.source_id,
displayed_name: val.displayed_name,
email: val.email,
}
}
}
@@ -104,9 +104,9 @@ impl AuthOidcService for AuthOidcServiceImpl {
Ok(OidcClaimsResponseDto {
sub: claims.subject().to_string(),
issuer: issuer,
preferred_username: preferred_username,
email: email,
issuer,
preferred_username,
email,
})
}
}
@@ -75,10 +75,12 @@ impl ImageController for ImageControllerImpl {
}
let mime_type = image.mime_type.clone();
let size = Some(image.data.len() as i64);
let id = self.upload_image_use_case.execute(image.into()).await?;
Ok(ImageInfoResponseDto {
id: id,
mime_type: mime_type,
id,
mime_type,
size,
is_referred: false,
})
}
@@ -97,6 +99,7 @@ impl ImageController for ImageControllerImpl {
Ok(ImageInfoResponseDto {
id: image_info.id,
mime_type: image_info.mime_type,
size: image_info.size,
is_referred: image_info.is_referred,
})
}
@@ -108,6 +111,7 @@ impl ImageController for ImageControllerImpl {
.map(|info| ImageInfoResponseDto {
id: info.id,
mime_type: info.mime_type,
size: info.size,
is_referred: info.is_referred,
})
.collect())
@@ -5,5 +5,6 @@ use utoipa::ToSchema;
pub struct ImageInfoResponseDto {
pub id: i32,
pub mime_type: String,
pub size: Option<i64>,
pub is_referred: bool,
}
@@ -5,11 +5,11 @@ pub struct ImageRequestDto {
pub data: Vec<u8>,
}
impl Into<CreateImageParams> for ImageRequestDto {
fn into(self) -> CreateImageParams {
impl From<ImageRequestDto> for CreateImageParams {
fn from(val: ImageRequestDto) -> Self {
CreateImageParams {
mime_type: self.mime_type,
data: self.data,
mime_type: val.mime_type,
data: val.data,
}
}
}
@@ -8,6 +8,10 @@ use crate::{
pub trait ImageDbService: Send + Sync {
async fn create_image_info(&self, image: ImageDbMapper) -> Result<i32, ImageError>;
async fn get_image_meta_data_by_id(&self, id: i32) -> Result<ImageDbMapper, ImageError>;
async fn get_image_meta_data_by_ids(
&self,
ids: &[i32],
) -> Result<Vec<ImageDbMapper>, ImageError>;
async fn list_image_meta_data(&self) -> Result<Vec<ImageDbMapper>, ImageError>;
async fn delete_image(&self, id: i32) -> Result<(), ImageError>;
}
@@ -1,3 +1,4 @@
use std::collections::HashMap;
use std::sync::Arc;
use async_trait::async_trait;
@@ -31,6 +32,18 @@ impl ImageRepositoryImpl {
image_storage,
}
}
/// Builds metadata from a database record. The size comes from the storage layer and is
/// optional: a record whose data file is missing or unreadable still yields usable
/// metadata, so a single broken image cannot fail the list, info, sitemap or feed
/// requests that read it.
fn to_image_meta_data(&self, image_db_mapper: ImageDbMapper) -> ImageMetaData {
ImageMetaData {
id: image_db_mapper.id,
mime_type: image_db_mapper.mime_type,
size: self.image_storage.size(image_db_mapper.id).ok(),
}
}
}
#[async_trait]
@@ -55,6 +68,7 @@ impl ImageRepository for ImageRepositoryImpl {
info: ImageMetaData {
id: image_db_mapper.id,
mime_type: image_db_mapper.mime_type,
size: Some(data.len() as i64),
},
data,
})
@@ -62,10 +76,25 @@ impl ImageRepository for ImageRepositoryImpl {
async fn get_image_meta_data_by_id(&self, id: i32) -> Result<ImageMetaData, ImageError> {
let image_db_mapper = self.image_db_service.get_image_meta_data_by_id(id).await?;
Ok(ImageMetaData {
id: image_db_mapper.id,
mime_type: image_db_mapper.mime_type,
})
Ok(self.to_image_meta_data(image_db_mapper))
}
async fn get_image_meta_data_by_ids(
&self,
ids: &[i32],
) -> Result<HashMap<i32, ImageMetaData>, ImageError> {
let image_db_mappers = self
.image_db_service
.get_image_meta_data_by_ids(ids)
.await?;
let mut image_meta_data = HashMap::new();
for image_db_mapper in image_db_mappers {
let meta_data = self.to_image_meta_data(image_db_mapper);
image_meta_data.insert(meta_data.id, meta_data);
}
Ok(image_meta_data)
}
async fn list_image_meta_data(&self) -> Result<Vec<ImageMetaData>, ImageError> {
@@ -73,10 +102,7 @@ impl ImageRepository for ImageRepositoryImpl {
Ok(image_db_mappers
.into_iter()
.map(|image_db_mapper| ImageMetaData {
id: image_db_mapper.id,
mime_type: image_db_mapper.mime_type,
})
.map(|image_db_mapper| self.to_image_meta_data(image_db_mapper))
.collect())
}
@@ -3,5 +3,6 @@ use crate::domain::error::image_error::ImageError;
pub trait ImageStorage: Send + Sync {
fn write_data(&self, id: i32, data: &[u8]) -> Result<(), ImageError>;
fn read_data(&self, id: i32) -> Result<Vec<u8>, ImageError>;
fn size(&self, id: i32) -> Result<i64, ImageError>;
fn delete_data(&self, id: i32) -> Result<(), ImageError>;
}
@@ -1,5 +1,6 @@
pub struct ImageInfo {
pub id: i32,
pub mime_type: String,
pub size: Option<i64>,
pub is_referred: bool,
}
@@ -7,12 +7,17 @@ use crate::{
error::image_error::ImageError,
},
};
use std::collections::HashMap;
#[async_trait]
pub trait ImageRepository: Send + Sync {
async fn save_image(&self, image: CreateImageParams) -> Result<i32, ImageError>;
async fn get_image_by_id(&self, id: i32) -> Result<Image, ImageError>;
async fn get_image_meta_data_by_id(&self, id: i32) -> Result<ImageMetaData, ImageError>;
async fn get_image_meta_data_by_ids(
&self,
ids: &[i32],
) -> Result<HashMap<i32, ImageMetaData>, ImageError>;
async fn list_image_meta_data(&self) -> Result<Vec<ImageMetaData>, ImageError>;
async fn delete_image(&self, id: i32) -> Result<(), ImageError>;
}
@@ -41,6 +41,7 @@ impl GetImageInfoUseCase for GetImageInfoUseCaseImpl {
Ok(ImageInfo {
id: image_meta_data.id,
mime_type: image_meta_data.mime_type,
size: image_meta_data.size,
is_referred,
})
}
@@ -50,6 +50,7 @@ impl ListImagesUseCase for ListImagesUseCaseImpl {
.map(|meta_data| ImageInfo {
id: meta_data.id,
mime_type: meta_data.mime_type,
size: meta_data.size,
is_referred: reference_counts.get(&meta_data.id).copied().unwrap_or(0) > 0,
})
.collect();
@@ -1,4 +1,8 @@
pub struct ImageMetaData {
pub id: i32,
pub mime_type: String,
/// Size of the stored data in bytes, or `None` when the data cannot be read (for example
/// when the file is missing). The record itself is still meaningful without it, so an
/// unreadable file does not fail the request that reads this metadata.
pub size: Option<i64>,
}
@@ -9,9 +9,9 @@ pub enum ImageError {
Unexpected(anyhow::Error),
}
impl Into<String> for ImageError {
fn into(self) -> String {
format!("{}", self)
impl From<ImageError> for String {
fn from(val: ImageError) -> Self {
format!("{}", val)
}
}
@@ -64,6 +64,35 @@ impl ImageDbService for ImageDbServiceImpl {
}
}
async fn get_image_meta_data_by_ids(
&self,
ids: &[i32],
) -> Result<Vec<ImageDbMapper>, ImageError> {
if ids.is_empty() {
return Ok(Vec::new());
}
let image_records = sqlx::query_as::<_, ImageRecord>(
r#"
SELECT id, mime_type
FROM image
WHERE id = ANY($1) AND deleted_time IS NULL
"#,
)
.bind(ids)
.fetch_all(&self.db_pool)
.await
.map_err(|e| ImageError::Unexpected(DatabaseError(e).into()))?;
Ok(image_records
.into_iter()
.map(|record| ImageDbMapper {
id: record.id,
mime_type: record.mime_type,
})
.collect())
}
async fn list_image_meta_data(&self) -> Result<Vec<ImageDbMapper>, ImageError> {
let image_records = sqlx::query_as!(
ImageRecord,
@@ -10,20 +10,20 @@ use crate::{
};
pub struct ImageStorageImpl {
sotrage_path: String,
storage_path: String,
}
impl ImageStorageImpl {
pub fn new(storage_path: &str) -> Self {
ImageStorageImpl {
sotrage_path: storage_path.to_string(),
storage_path: storage_path.to_string(),
}
}
}
impl ImageStorage for ImageStorageImpl {
fn write_data(&self, id: i32, data: &[u8]) -> Result<(), ImageError> {
let dir_path = format!("{}/images", self.sotrage_path);
let dir_path = format!("{}/images", self.storage_path);
fs::create_dir_all(&dir_path).map_err(|e| ImageError::Unexpected(IOError(e).into()))?;
let file_path = format!("{}/{}", dir_path, id);
@@ -36,13 +36,20 @@ impl ImageStorage for ImageStorageImpl {
}
fn read_data(&self, id: i32) -> Result<Vec<u8>, ImageError> {
let file_path = format!("{}/images/{}", self.sotrage_path, id);
let file_path = format!("{}/images/{}", self.storage_path, id);
let data = fs::read(&file_path).map_err(|e| ImageError::Unexpected(IOError(e).into()))?;
Ok(data)
}
fn size(&self, id: i32) -> Result<i64, ImageError> {
let file_path = format!("{}/images/{}", self.storage_path, id);
let metadata =
fs::metadata(&file_path).map_err(|e| ImageError::Unexpected(IOError(e).into()))?;
Ok(metadata.len() as i64)
}
fn delete_data(&self, id: i32) -> Result<(), ImageError> {
let file_path = format!("{}/images/{}", self.sotrage_path, id);
let file_path = format!("{}/images/{}", self.storage_path, id);
fs::remove_file(&file_path).map_err(|e| ImageError::Unexpected(IOError(e).into()))?;
Ok(())
}
@@ -11,13 +11,13 @@ pub struct ColorRequestDto {
pub alpha: u8,
}
impl Into<Color> for ColorRequestDto {
fn into(self) -> Color {
impl From<ColorRequestDto> for Color {
fn from(val: ColorRequestDto) -> Self {
Color {
red: self.red,
green: self.green,
blue: self.blue,
alpha: self.alpha,
red: val.red,
green: val.green,
blue: val.blue,
alpha: val.alpha,
}
}
}
@@ -12,11 +12,11 @@ pub struct CreateLabelRequestDto {
pub color: ColorRequestDto,
}
impl Into<CreateOrUpdateLabelParams> for CreateLabelRequestDto {
fn into(self) -> CreateOrUpdateLabelParams {
impl From<CreateLabelRequestDto> for CreateOrUpdateLabelParams {
fn from(val: CreateLabelRequestDto) -> Self {
CreateOrUpdateLabelParams {
name: self.name,
color: self.color.into(),
name: val.name,
color: val.color.into(),
}
}
}
@@ -81,7 +81,7 @@ impl LabelController for LabelControllerImpl {
Ok(result
.into_iter()
.map(|label| LabelResponseDto::from(label))
.map(LabelResponseDto::from)
.collect())
}
@@ -12,11 +12,11 @@ pub struct UpdateLabelRequestDto {
pub color: ColorRequestDto,
}
impl Into<CreateOrUpdateLabelParams> for UpdateLabelRequestDto {
fn into(self) -> CreateOrUpdateLabelParams {
impl From<UpdateLabelRequestDto> for CreateOrUpdateLabelParams {
fn from(val: UpdateLabelRequestDto) -> Self {
CreateOrUpdateLabelParams {
name: self.name,
color: self.color.into(),
name: val.name,
color: val.color.into(),
}
}
}
@@ -4,13 +4,13 @@ pub struct ColorMapper {
pub value: u32,
}
impl Into<Color> for ColorMapper {
fn into(self) -> Color {
impl From<ColorMapper> for Color {
fn from(val: ColorMapper) -> Self {
Color {
red: (self.value >> 24) as u8,
green: ((self.value >> 16) & 0xFF) as u8,
blue: ((self.value >> 8) & 0xFF) as u8,
alpha: (self.value & 0xFF) as u8,
red: (val.value >> 24) as u8,
green: ((val.value >> 16) & 0xFF) as u8,
blue: ((val.value >> 8) & 0xFF) as u8,
alpha: (val.value & 0xFF) as u8,
}
}
}
@@ -6,12 +6,12 @@ pub struct LabelMapper {
pub color: ColorMapper,
}
impl Into<Label> for LabelMapper {
fn into(self) -> Label {
impl From<LabelMapper> for Label {
fn from(val: LabelMapper) -> Self {
Label {
id: self.id,
name: self.name,
color: self.color.into(),
id: val.id,
name: val.name,
color: val.color.into(),
}
}
}
@@ -7,9 +7,9 @@ pub enum LabelError {
Unexpected(anyhow::Error),
}
impl Into<String> for LabelError {
fn into(self) -> String {
format!("{}", self)
impl From<LabelError> for String {
fn from(val: LabelError) -> Self {
format!("{}", val)
}
}
@@ -33,11 +33,10 @@ impl LabelDbService for LabelDbServiceImpl {
.fetch_one(&self.db_pool)
.await
.map_err(|e| {
if let sqlx::Error::Database(db_err) = &e {
if db_err.constraint() == Some("idx_label_name") {
if let sqlx::Error::Database(db_err) = &e
&& db_err.constraint() == Some("idx_label_name") {
return LabelError::DuplicatedLabelName;
}
}
LabelError::Unexpected(DatabaseError(e).into())
})?;
@@ -58,11 +57,10 @@ impl LabelDbService for LabelDbServiceImpl {
.execute(&self.db_pool)
.await
.map_err(|e| {
if let sqlx::Error::Database(db_err) = &e {
if db_err.constraint() == Some("idx_label_name") {
if let sqlx::Error::Database(db_err) = &e
&& db_err.constraint() == Some("idx_label_name") {
return LabelError::DuplicatedLabelName;
}
}
LabelError::Unexpected(DatabaseError(e).into())
})?
.rows_affected();
@@ -22,18 +22,18 @@ pub struct CreatePostRequestDto {
pub published_time: Option<String>,
}
impl Into<CreatePostParams> for CreatePostRequestDto {
fn into(self) -> CreatePostParams {
let image_ids = ImageExtractor::extract_image_ids(&self.content, &self.preview_image_url);
impl From<CreatePostRequestDto> for CreatePostParams {
fn from(val: CreatePostRequestDto) -> Self {
let image_ids = ImageExtractor::extract_image_ids(&val.content, &val.preview_image_url);
CreatePostParams {
semantic_id: self.semantic_id,
title: self.title,
description: self.description,
content: self.content,
label_ids: self.label_ids,
preview_image_url: self.preview_image_url,
published_time: self
semantic_id: val.semantic_id,
title: val.title,
description: val.description,
content: val.content,
label_ids: val.label_ids,
preview_image_url: val.preview_image_url,
published_time: val
.published_time
.and_then(|time_str| DateTime::parse_from_rfc3339(&time_str).ok())
.map(|dt| dt.with_timezone(&Utc)),
@@ -115,7 +115,7 @@ impl PostController for PostControllerImpl {
result.map(|post_info_list| {
let post_info_response_dto_list: Vec<PostInfoResponseDto> = post_info_list
.into_iter()
.map(|post_info| PostInfoResponseDto::from(post_info))
.map(PostInfoResponseDto::from)
.collect();
post_info_response_dto_list
@@ -15,8 +15,15 @@ pub struct PostInfoResponseDto {
#[schema(format = Uri)]
pub preview_image_url: Option<String>,
pub preview_image_mime_type: Option<String>,
pub preview_image_size: Option<i64>,
#[schema(format = DateTime)]
pub published_time: Option<String>,
#[schema(format = DateTime)]
pub updated_time: Option<String>,
}
impl From<PostInfo> for PostInfoResponseDto {
@@ -27,12 +34,15 @@ impl From<PostInfo> for PostInfoResponseDto {
title: entity.title,
description: entity.description,
preview_image_url: entity.preview_image_url,
preview_image_mime_type: entity.preview_image_mime_type,
preview_image_size: entity.preview_image_size,
labels: entity
.labels
.into_iter()
.map(LabelResponseDto::from)
.collect(),
published_time: entity.published_time.map(|datetime| datetime.to_rfc3339()),
updated_time: entity.updated_time.map(|datetime| datetime.to_rfc3339()),
}
}
}
@@ -21,17 +21,17 @@ pub struct UpdatePostRequestDto {
pub published_time: Option<String>,
}
impl Into<UpdatePostParams> for UpdatePostRequestDto {
fn into(self) -> UpdatePostParams {
let image_ids = ImageExtractor::extract_image_ids(&self.content, &self.preview_image_url);
impl From<UpdatePostRequestDto> for UpdatePostParams {
fn from(val: UpdatePostRequestDto) -> Self {
let image_ids = ImageExtractor::extract_image_ids(&val.content, &val.preview_image_url);
UpdatePostParams {
title: self.title,
description: self.description,
content: self.content,
label_ids: self.label_ids,
preview_image_url: self.preview_image_url,
published_time: self
title: val.title,
description: val.description,
content: val.content,
label_ids: val.label_ids,
preview_image_url: val.preview_image_url,
published_time: val
.published_time
.and_then(|time_str| DateTime::parse_from_rfc3339(&time_str).ok())
.map(|dt| dt.with_timezone(&Utc)),
@@ -6,12 +6,12 @@ pub struct PostMapper {
pub content: String,
}
impl Into<Post> for PostMapper {
fn into(self) -> Post {
impl From<PostMapper> for Post {
fn from(val: PostMapper) -> Self {
Post {
id: self.id,
info: self.info.into(),
content: self.content,
id: val.id,
info: val.info.into(),
content: val.content,
}
}
}
@@ -10,21 +10,28 @@ pub struct PostInfoMapper {
pub description: String,
pub preview_image_url: Option<String>,
pub published_time: Option<NaiveDateTime>,
pub updated_time: Option<NaiveDateTime>,
pub labels: Vec<LabelMapper>,
}
impl Into<PostInfo> for PostInfoMapper {
fn into(self) -> PostInfo {
impl From<PostInfoMapper> for PostInfo {
fn from(val: PostInfoMapper) -> Self {
PostInfo {
id: self.id,
semantic_id: self.semantic_id,
title: self.title,
description: self.description,
preview_image_url: self.preview_image_url,
published_time: self
id: val.id,
semantic_id: val.semantic_id,
title: val.title,
description: val.description,
preview_image_url: val.preview_image_url,
// Filled in by the use case from the image feature when needed.
preview_image_mime_type: None,
preview_image_size: None,
published_time: val
.published_time
.map(|dt| DateTime::<Utc>::from_naive_utc_and_offset(dt, Utc)),
labels: self.labels.into_iter().map(Into::into).collect(),
updated_time: val
.updated_time
.map(|dt| DateTime::<Utc>::from_naive_utc_and_offset(dt, Utc)),
labels: val.labels.into_iter().map(Into::into).collect(),
}
}
}
@@ -65,6 +65,7 @@ impl PostRepository for PostRepositoryImpl {
preview_image_url: post.preview_image_url,
labels: Vec::new(),
published_time: post.published_time.map(|dt| dt.naive_utc()),
updated_time: None,
};
let post_mapper = PostMapper {
@@ -80,17 +81,18 @@ impl PostRepository for PostRepositoryImpl {
async fn update_post(&self, id: i32, post: UpdatePostParams) -> Result<(), PostError> {
let info_mapper = PostInfoMapper {
id: id,
id,
semantic_id: String::new(),
title: post.title,
description: post.description,
preview_image_url: post.preview_image_url,
labels: Vec::new(),
published_time: post.published_time.map(|dt| dt.naive_utc()),
updated_time: None,
};
let post_mapper = PostMapper {
id: id,
id,
info: info_mapper,
content: post.content,
};
@@ -1,2 +1,3 @@
pub mod image_extractor;
pub mod label_relation_service;
pub mod preview_image_metadata_service;
@@ -1,37 +1,44 @@
use regex::Regex;
use std::collections::HashSet;
use std::{collections::HashSet, sync::LazyLock};
/// Matches the trailing path segments of an image URL and captures its id, for example the `42`
/// in `/image/42`.
static IMAGE_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r#"(\/[^\/\s]+)*\/image\/(\d+)"#).unwrap());
/// Matches a markdown image whose target is an [`IMAGE_REGEX`] match.
static MARKDOWN_IMAGE_REGEX: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(&format!(
"{}{}{}",
r#"!\[.*\]\("#,
IMAGE_REGEX.as_str(),
r#"\)"#
))
.unwrap()
});
pub struct ImageExtractor;
impl ImageExtractor {
pub fn extract_preview_image_id(preview_image_url: &Option<String>) -> Option<i32> {
let url = preview_image_url.as_ref()?;
let cap = IMAGE_REGEX.captures(url)?;
cap.get(2)?.as_str().parse::<i32>().ok()
}
pub fn extract_image_ids(content: &str, preview_image_url: &Option<String>) -> Vec<i32> {
let mut image_ids = HashSet::new();
let image_re = Regex::new(r#"(\/[^\/\s]+)*\/image\/(\d+)"#).unwrap();
let md_image_re = Regex::new(&format!(
"{}{}{}",
r#"!\[.*\]\("#,
image_re.as_str(),
r#"\)"#
))
.unwrap();
for cap in md_image_re.captures_iter(content) {
if let Some(id_str) = cap.get(2) {
if let Ok(id) = id_str.as_str().parse::<i32>() {
image_ids.insert(id);
}
for cap in MARKDOWN_IMAGE_REGEX.captures_iter(content) {
if let Some(id_str) = cap.get(2)
&& let Ok(id) = id_str.as_str().parse::<i32>()
{
image_ids.insert(id);
}
}
if let Some(url) = preview_image_url {
if let Some(cap) = image_re.captures(url) {
if let Some(id_str) = cap.get(2) {
if let Ok(id) = id_str.as_str().parse::<i32>() {
image_ids.insert(id);
}
}
}
if let Some(id) = Self::extract_preview_image_id(preview_image_url) {
image_ids.insert(id);
}
image_ids.into_iter().collect()
@@ -65,4 +72,25 @@ mod tests {
let ids = ImageExtractor::extract_image_ids(content, &preview_image_url);
assert_eq!(ids, vec![789]);
}
#[test]
fn test_extract_preview_image_id_only() {
assert_eq!(
ImageExtractor::extract_preview_image_id(&Some("/image/42".to_string())),
Some(42)
);
assert_eq!(
ImageExtractor::extract_preview_image_id(&Some(
"https://example.com/image/7".to_string()
)),
Some(7)
);
assert_eq!(
ImageExtractor::extract_preview_image_id(&Some(
"https://example.com/photo.png".to_string()
)),
None
);
assert_eq!(ImageExtractor::extract_preview_image_id(&None), None);
}
}
@@ -13,7 +13,7 @@ impl LabelRelationService {
label_repository
.get_label_by_id(label_id)
.await
.map_err(|e| PostError::LabelError(e.into()))?;
.map_err(PostError::LabelError)?;
}
Ok(())
@@ -0,0 +1,45 @@
use std::sync::Arc;
use image::application::gateway::image_repository::ImageRepository;
use crate::{
application::service::image_extractor::ImageExtractor,
domain::{entity::post_info::PostInfo, error::post_error::PostError},
};
/// Attaches the preview image's MIME type and size to posts. The metadata lives in the image
/// feature, so it cannot be read as part of the post query; consumers such as the RSS feed need
/// it to emit a valid `<enclosure>`.
pub struct PreviewImageMetadataService;
impl PreviewImageMetadataService {
pub async fn attach(
image_repository: Arc<dyn ImageRepository>,
posts: &mut [PostInfo],
) -> Result<(), PostError> {
// Resolve each id once so the second pass only has to look the metadata up.
let preview_image_ids: Vec<Option<i32>> = posts
.iter()
.map(|post| ImageExtractor::extract_preview_image_id(&post.preview_image_url))
.collect();
let image_ids: Vec<i32> = preview_image_ids.iter().flatten().copied().collect();
if image_ids.is_empty() {
return Ok(());
}
let image_meta_data = image_repository
.get_image_meta_data_by_ids(&image_ids)
.await
.map_err(|e| PostError::Unexpected(anyhow::anyhow!(e.to_string())))?;
for (post, image_id) in posts.iter_mut().zip(preview_image_ids) {
if let Some(meta_data) = image_id.and_then(|id| image_meta_data.get(&id)) {
post.preview_image_mime_type = Some(meta_data.mime_type.clone());
post.preview_image_size = meta_data.size;
}
}
Ok(())
}
}
@@ -1,9 +1,13 @@
use std::{collections::HashMap, sync::Arc};
use async_trait::async_trait;
use image::application::gateway::image_repository::ImageRepository;
use crate::{
application::gateway::{post_repository::PostRepository, search_service::SearchService},
application::{
gateway::{post_repository::PostRepository, search_service::SearchService},
service::preview_image_metadata_service::PreviewImageMetadataService,
},
domain::{entity::post_info::PostInfo, error::post_error::PostError},
};
@@ -21,16 +25,19 @@ pub trait GetAllPostInfoUseCase: Send + Sync {
pub struct GetAllPostInfoUseCaseImpl {
post_repository: Arc<dyn PostRepository>,
search_service: Arc<dyn SearchService>,
image_repository: Arc<dyn ImageRepository>,
}
impl GetAllPostInfoUseCaseImpl {
pub fn new(
post_repository: Arc<dyn PostRepository>,
search_service: Arc<dyn SearchService>,
image_repository: Arc<dyn ImageRepository>,
) -> Self {
Self {
post_repository,
search_service,
image_repository,
}
}
}
@@ -54,11 +61,13 @@ impl GetAllPostInfoUseCase for GetAllPostInfoUseCaseImpl {
// | F | F | T |
let is_published_only = is_published_only || !has_logged_in;
let posts = self
let mut posts = self
.post_repository
.get_all_post_info(is_published_only, label_id)
.await?;
PreviewImageMetadataService::attach(self.image_repository.clone(), &mut posts).await?;
if let Some(keyword) = keyword {
let post_map: HashMap<i32, PostInfo> =
HashMap::from_iter(posts.into_iter().map(|post_info| (post_info.id, post_info)));
@@ -1,9 +1,13 @@
use std::sync::Arc;
use async_trait::async_trait;
use image::application::gateway::image_repository::ImageRepository;
use crate::{
application::gateway::post_repository::PostRepository,
application::{
gateway::post_repository::PostRepository,
service::preview_image_metadata_service::PreviewImageMetadataService,
},
domain::{entity::post::Post, error::post_error::PostError},
};
@@ -14,23 +18,36 @@ pub trait GetPostByIdUseCase: Send + Sync {
pub struct GetFullPostUseCaseImpl {
post_repository: Arc<dyn PostRepository>,
image_repository: Arc<dyn ImageRepository>,
}
impl GetFullPostUseCaseImpl {
pub fn new(post_repository: Arc<dyn PostRepository>) -> Self {
Self { post_repository }
pub fn new(
post_repository: Arc<dyn PostRepository>,
image_repository: Arc<dyn ImageRepository>,
) -> Self {
Self {
post_repository,
image_repository,
}
}
}
#[async_trait]
impl GetPostByIdUseCase for GetFullPostUseCaseImpl {
async fn execute(&self, id: i32, user_id: Option<i32>) -> Result<Post, PostError> {
let post = self.post_repository.get_post_by_id(id).await?;
let mut post = self.post_repository.get_post_by_id(id).await?;
if post.info.published_time.is_none() && user_id.is_none() {
return Err(PostError::NotFound);
}
PreviewImageMetadataService::attach(
self.image_repository.clone(),
std::slice::from_mut(&mut post.info),
)
.await?;
Ok(post)
}
}
@@ -11,8 +11,11 @@ pub struct PostInfo {
pub title: String,
pub description: String,
pub preview_image_url: Option<String>,
pub preview_image_mime_type: Option<String>,
pub preview_image_size: Option<i64>,
pub labels: Vec<Label>,
pub published_time: Option<DateTime<Utc>>,
pub updated_time: Option<DateTime<Utc>>,
}
impl PostInfo {
@@ -11,9 +11,9 @@ pub enum PostError {
Unexpected(anyhow::Error),
}
impl Into<String> for PostError {
fn into(self) -> String {
format!("{}", self)
impl From<PostError> for String {
fn from(val: PostError) -> Self {
format!("{}", val)
}
}
@@ -93,6 +93,7 @@ impl PostDbService for PostDbServiceImpl {
preview_image_url: record.preview_image_url.clone(),
labels: Vec::new(),
published_time: record.published_time,
updated_time: record.updated_time,
});
if let (Some(label_id), Some(label_name), Some(label_color)) = (
@@ -131,6 +132,7 @@ impl PostDbService for PostDbServiceImpl {
p.preview_image_url,
p.content,
p.published_time,
p.updated_time,
l.id AS label_id,
l.name AS label_name,
l.color AS label_color
@@ -173,6 +175,7 @@ impl PostDbService for PostDbServiceImpl {
preview_image_url: record.preview_image_url.clone(),
labels: Vec::new(),
published_time: record.published_time,
updated_time: record.updated_time,
},
content: record.content.clone(),
});
@@ -229,11 +232,10 @@ impl PostDbService for PostDbServiceImpl {
.fetch_one(&mut *tx)
.await
.map_err(|e| {
if let sqlx::Error::Database(db_err) = &e {
if db_err.constraint() == Some("idx_post_semantic_id") {
if let sqlx::Error::Database(db_err) = &e
&& db_err.constraint() == Some("idx_post_semantic_id") {
return PostError::DuplicatedSemanticId;
}
}
PostError::Unexpected(DatabaseError(e).into())
})?;
@@ -292,11 +294,11 @@ impl PostDbService for PostDbServiceImpl {
let affected_rows = sqlx::query!(
r#"
UPDATE post
SET
title = $1,
description = $2,
preview_image_url = $3,
content = $4,
SET
title = $1,
description = $2,
preview_image_url = $3,
content = $4,
published_time = $5
WHERE id = $6
"#,
@@ -310,11 +312,10 @@ impl PostDbService for PostDbServiceImpl {
.execute(&mut *tx)
.await
.map_err(|e| {
if let sqlx::Error::Database(db_err) = &e {
if db_err.constraint() == Some("idx_post_semantic_id") {
if let sqlx::Error::Database(db_err) = &e
&& db_err.constraint() == Some("idx_post_semantic_id") {
return PostError::DuplicatedSemanticId;
}
}
PostError::Unexpected(DatabaseError(e).into())
})?
.rows_affected();
@@ -8,6 +8,7 @@ pub struct PostInfoWithLabelRecord {
pub description: String,
pub preview_image_url: Option<String>,
pub published_time: Option<NaiveDateTime>,
pub updated_time: Option<NaiveDateTime>,
pub label_id: Option<i32>,
pub label_name: Option<String>,
@@ -9,6 +9,7 @@ pub struct PostWithLabelRecord {
pub preview_image_url: Option<String>,
pub content: String,
pub published_time: Option<NaiveDateTime>,
pub updated_time: Option<NaiveDateTime>,
pub label_id: Option<i32>,
pub label_name: Option<String>,
@@ -12,6 +12,6 @@ pub trait SearchQueryEmbeddingCache: Send + Sync {
async fn set_by_query_string(
&self,
query_string: &str,
embedding: &Vec<f32>,
embedding: &[f32],
) -> Result<(), SearchError>;
}
}
@@ -78,17 +78,21 @@ impl SearchRepository for SearchRepositoryImpl {
impl SearchRepositoryImpl {
fn split_markdown(&self, markdown: &str) -> Vec<String> {
self.markdown_splitter
.chunks(&markdown)
.chunks(markdown)
.map(|s| s.to_string())
.collect()
}
async fn get_query_embedding(&self, query_string: &str) -> Result<Vec<f32>, SearchError> {
if let Ok(Some(cached_embedding)) = self.query_embedding_cache.get_by_query_string(query_string).await {
if let Ok(Some(cached_embedding)) = self
.query_embedding_cache
.get_by_query_string(query_string)
.await
{
return Ok(cached_embedding);
}
let embeddings = self.embed_chunks(&vec![query_string.to_string()]).await?;
let embeddings = self.embed_chunks(&[query_string.to_string()]).await?;
let query_vector = embeddings
.into_iter()
.next()
@@ -104,9 +108,9 @@ impl SearchRepositoryImpl {
Ok(query_vector)
}
async fn embed_chunks(&self, chunks: &Vec<String>) -> Result<Vec<Vec<f32>>, SearchError> {
async fn embed_chunks(&self, chunks: &[String]) -> Result<Vec<Vec<f32>>, SearchError> {
let model = self.text_embedding_model.clone();
let chunks = chunks.clone();
let chunks = chunks.to_owned();
spawn_blocking(move || {
let mut model = model.blocking_lock();
@@ -114,6 +118,6 @@ impl SearchRepositoryImpl {
})
.await
.map_err(|e| SearchError::Unexpected(e.into()))?
.map_err(|e| SearchError::Unexpected(e.into()))
.map_err(SearchError::Unexpected)
}
}
@@ -4,17 +4,13 @@ use crate::domain::error::search_error::SearchError;
#[async_trait]
pub trait SearchVectorDbService: Send + Sync {
async fn insert_vectors(
&self,
post_id: i32,
vectors: &Vec<Vec<f32>>,
) -> Result<(), SearchError>;
async fn insert_vectors(&self, post_id: i32, vectors: &[Vec<f32>]) -> Result<(), SearchError>;
async fn delete_vectors_by_post_id(&self, post_id: i32) -> Result<(), SearchError>;
async fn search_similar_posts(
&self,
query_vector: &Vec<f32>,
query_vector: &[f32],
scope: &Option<Vec<i32>>,
) -> Result<Vec<i32>, SearchError>;
}
@@ -5,9 +5,9 @@ pub enum SearchError {
Unexpected(anyhow::Error),
}
impl Into<String> for SearchError {
fn into(self) -> String {
format!("{}", self)
impl From<SearchError> for String {
fn from(val: SearchError) -> Self {
format!("{}", val)
}
}
@@ -58,7 +58,7 @@ impl SearchQueryEmbeddingCache for SearchQueryEmbeddingCacheRedisImpl {
async fn set_by_query_string(
&self,
query_string: &str,
embedding: &Vec<f32>,
embedding: &[f32],
) -> Result<(), SearchError> {
let key = self.generate_cache_key(query_string);
let value =
@@ -43,13 +43,9 @@ impl SearchVectorDbServiceImpl {
#[async_trait]
impl SearchVectorDbService for SearchVectorDbServiceImpl {
async fn insert_vectors(
&self,
post_id: i32,
vectors: &Vec<Vec<f32>>,
) -> Result<(), SearchError> {
async fn insert_vectors(&self, post_id: i32, vectors: &[Vec<f32>]) -> Result<(), SearchError> {
let points: Vec<PointStruct> = vectors
.into_iter()
.iter()
.enumerate()
.map(|(index, vector)| {
let payload = InnerPayload {
@@ -87,7 +83,7 @@ impl SearchVectorDbService for SearchVectorDbServiceImpl {
async fn search_similar_posts(
&self,
query_vector: &Vec<f32>,
query_vector: &[f32],
scope: &Option<Vec<i32>>,
) -> Result<Vec<i32>, SearchError> {
let filter = if let Some(scope) = scope {
@@ -103,7 +99,7 @@ impl SearchVectorDbService for SearchVectorDbServiceImpl {
};
let request = QueryPointGroupsBuilder::new(self.collection_name.clone(), KEY_POST_ID)
.query(query_vector.clone())
.query(query_vector.to_owned())
.with_payload(true)
.filter(filter)
.group_size(1u64)
+6
View File
@@ -7,6 +7,12 @@ pub struct DbConfiguration {
pub database_url: String,
}
impl Default for DbConfiguration {
fn default() -> Self {
Self::new()
}
}
impl DbConfiguration {
pub fn new() -> Self {
let host = env::var("DATABASE_HOST").unwrap_or_else(|_| "127.0.0.1".to_string());
@@ -13,6 +13,12 @@ pub struct EmbeddingConfiguration {
overlap_token: usize,
}
impl Default for EmbeddingConfiguration {
fn default() -> Self {
Self::new()
}
}
impl EmbeddingConfiguration {
pub fn new() -> Self {
let cache_dir = std::env::var("EMBEDDING_CACHE_PATH")
@@ -14,6 +14,12 @@ pub struct QdrantConfiguration {
size: u64,
}
impl Default for QdrantConfiguration {
fn default() -> Self {
Self::new()
}
}
impl QdrantConfiguration {
pub fn new() -> Self {
let url =
@@ -7,6 +7,12 @@ pub struct RedisConfiguration {
pub search_query_embedding_prefix: String,
}
impl Default for RedisConfiguration {
fn default() -> Self {
Self::new()
}
}
impl RedisConfiguration {
pub fn new() -> Self {
let url =
+7 -1
View File
@@ -4,12 +4,18 @@ pub struct SentryConfiguration {
pub options: sentry::ClientOptions,
}
impl Default for SentryConfiguration {
fn default() -> Self {
Self::new()
}
}
impl SentryConfiguration {
pub fn new() -> Self {
let dsn = std::env::var("SENTRY_DSN").unwrap_or("".to_string());
Self {
dsn: dsn,
dsn,
options: sentry::ClientOptions {
release: sentry::release_name!(),
traces_sample_rate: 1.0,
@@ -4,6 +4,12 @@ pub struct ServerConfiguration {
pub port: u16,
}
impl Default for ServerConfiguration {
fn default() -> Self {
Self::new()
}
}
impl ServerConfiguration {
pub fn new() -> Self {
let host = std::env::var("HOST").unwrap_or_else(|_| "127.0.0.1".to_string());
@@ -5,6 +5,12 @@ pub struct StorageConfiguration {
pub storage_path: String,
}
impl Default for StorageConfiguration {
fn default() -> Self {
Self::new()
}
}
impl StorageConfiguration {
pub fn new() -> Self {
let storage_path = env::var("STORAGE_PATH").unwrap_or_else(|_| "static".to_string());
+15 -10
View File
@@ -140,6 +140,16 @@ impl Container {
get_label_by_id_use_case,
));
// Image metadata is built before Post because the post use case enriches posts with
// their preview image's MIME type and size.
let image_db_service = Arc::new(ImageDbServiceImpl::new(db_pool.clone()));
let image_storage = Arc::new(ImageStorageImpl::new(&configuration.storage.storage_path));
let image_repository = Arc::new(ImageRepositoryImpl::new(
image_db_service.clone(),
image_storage.clone(),
));
// Search
let search_vector_db_service = Arc::new(SearchVectorDbServiceImpl::new(
qdrant_client,
@@ -178,9 +188,12 @@ impl Container {
let get_all_post_info_use_case = Arc::new(GetAllPostInfoUseCaseImpl::new(
post_repository.clone(),
search_service.clone(),
image_repository.clone(),
));
let get_post_by_id_use_case = Arc::new(GetFullPostUseCaseImpl::new(
post_repository.clone(),
image_repository.clone(),
));
let get_post_by_id_use_case =
Arc::new(GetFullPostUseCaseImpl::new(post_repository.clone()));
let get_post_by_semantic_id_use_case = Arc::new(GetPostBySemanticIdUseCaseImpl::new(
post_repository.clone(),
get_post_by_id_use_case.clone(),
@@ -205,14 +218,6 @@ impl Container {
));
// Image
let image_db_service = Arc::new(ImageDbServiceImpl::new(db_pool.clone()));
let image_storage = Arc::new(ImageStorageImpl::new(&configuration.storage.storage_path));
let image_repository = Arc::new(ImageRepositoryImpl::new(
image_db_service.clone(),
image_storage.clone(),
));
let upload_image_use_case = Arc::new(UploadImageUseCaseImpl::new(image_repository.clone()));
let get_image_use_case = Arc::new(GetImageUseCaseImpl::new(image_repository.clone()));
let get_image_info_use_case = Arc::new(GetImageInfoUseCaseImpl::new(
+1
View File
@@ -83,6 +83,7 @@ fn main() -> std::io::Result<()> {
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn create_app(
db_pool: sqlx::Pool<Postgres>,
redis_pool: deadpool_redis::Pool,
+12
View File
@@ -62,3 +62,15 @@ Each feature module in `src/lib/` follows the Clean Architecture pattern:
- **Type Safety**: TypeScript
- **Linting**: ESLint with Prettier
- **Package Manager**: bun
### Sitemap & Feed
The frontend serves its own discovery documents, so the public URL scheme is defined only here:
- `/sitemap.xml` - every published post plus the static pages the backend cannot know about
(home, post list, terms).
- `/feed.xml` - an RSS 2.0 feed of the 20 most recent posts. Items are identified by the post's
semantic id, so their `guid` stays stable when URLs change.
Both are generated on demand from `src/lib/seo/` and served with `Cache-Control: public, max-age=300`,
so a newly published post shows up without a rebuild or a separate generation step.
+40 -2
View File
@@ -31,6 +31,7 @@
"eslint-config-prettier": "10.1.8",
"eslint-plugin-simple-import-sort": "13.0.0",
"eslint-plugin-svelte": "3.17.1",
"feed": "6.0.0",
"globals": "17.5.0",
"highlight.js": "11.11.1",
"markdown-it": "14.1.1",
@@ -39,7 +40,8 @@
"prettier": "3.8.3",
"prettier-plugin-svelte": "3.5.1",
"prettier-plugin-tailwindcss": "0.7.2",
"sanitize-html": "2.17.3",
"sanitize-html": "2.17.7",
"sitemap": "9.0.1",
"svelte": "5.55.5",
"svelte-adapter-bun": "1.0.1",
"svelte-check": "4.4.6",
@@ -473,6 +475,8 @@
"@types/sanitize-html": ["@types/sanitize-html@2.16.1", "", { "dependencies": { "htmlparser2": "10.1.0" } }, "sha512-n9wjs8bCOTyN/ynwD8s/nTcTreIHB1vf31vhLMGqUPNHaweKC4/fAl4Dj+hUlCTKYgm4P3k83fmiFfzkZ6sgMA=="],
"@types/sax": ["@types/sax@1.2.7", "", { "dependencies": { "@types/node": "*" } }, "sha512-rO73L89PJxeYM3s3pPPjiPgVVcymqU490g0YO5n5By0k2Erzj6tay/4lr1CHAAU4JyOWd1rpQ8bCf6cZfHU96A=="],
"@types/tedious": ["@types/tedious@4.0.14", "", { "dependencies": { "@types/node": "22.19.17" } }, "sha512-KHPsfX/FoVbUGbyYvk1q9MMQHLPeRZhRJZdO45Q4YjvFkv4hMNghCWTvy7rdKessBsmtz4euWCWAB6/tVpI1Iw=="],
"@types/trusted-types": ["@types/trusted-types@2.0.7", "", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="],
@@ -509,6 +513,8 @@
"ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="],
"arg": ["arg@5.0.2", "", {}, "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg=="],
"argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
"aria-query": ["aria-query@5.3.1", "", {}, "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g=="],
@@ -553,6 +559,8 @@
"cssesc": ["cssesc@3.0.0", "", { "bin": { "cssesc": "bin/cssesc" } }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="],
"dayjs": ["dayjs@1.11.23", "", {}, "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ=="],
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"deep-is": ["deep-is@0.1.4", "", {}, "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ=="],
@@ -621,6 +629,8 @@
"fdir": ["fdir@6.5.0", "", { "optionalDependencies": { "picomatch": "4.0.4" } }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
"feed": ["feed@6.0.0", "", { "dependencies": { "xml-js": "^1.6.11" } }, "sha512-rvFOF1POce0ijAKy3tZN5T8PuprgIit/VbMyXJWcoYwcMOTSIJ7NqZb8DTLPJr77yiEO27kidm/fw0kcSIV+ww=="],
"file-entry-cache": ["file-entry-cache@8.0.0", "", { "dependencies": { "flat-cache": "4.0.1" } }, "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ=="],
"find-up": ["find-up@5.0.0", "", { "dependencies": { "locate-path": "6.0.0", "path-exists": "4.0.0" } }, "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng=="],
@@ -697,6 +707,8 @@
"known-css-properties": ["known-css-properties@0.37.0", "", {}, "sha512-JCDrsP4Z1Sb9JwG0aJ8Eo2r7k4Ou5MwmThS/6lcIe1ICyb7UBJKGRIUUdqc2ASdE/42lgz6zFUnzAIhtXnBVrQ=="],
"launder": ["launder@1.7.1", "", { "dependencies": { "dayjs": "^1.11.7" } }, "sha512-mU6WRz5EusL9ZZuiZ5SO4Y6C0P9PAUR9iwdb6bzj4KDihm28DiHFw+/yk9DBH4f+Pv1wuzQ4e2jV3oQ7mkIqvw=="],
"levn": ["levn@0.4.1", "", { "dependencies": { "prelude-ls": "1.2.1", "type-check": "0.4.0" } }, "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ=="],
"lightningcss": ["lightningcss@1.32.0", "", { "dependencies": { "detect-libc": "2.1.2" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],
@@ -845,7 +857,9 @@
"sade": ["sade@1.8.1", "", { "dependencies": { "mri": "1.2.0" } }, "sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A=="],
"sanitize-html": ["sanitize-html@2.17.3", "", { "dependencies": { "deepmerge": "4.3.1", "escape-string-regexp": "4.0.0", "htmlparser2": "10.1.0", "is-plain-object": "5.0.0", "parse-srcset": "1.0.2", "postcss": "8.5.8" } }, "sha512-Kn4srCAo2+wZyvCNKCSyB2g8RQ8IkX/gQs2uqoSRNu5t9I2qvUyAVvRDiFUVAiX3N3PNuwStY0eNr+ooBHVWEg=="],
"sanitize-html": ["sanitize-html@2.17.7", "", { "dependencies": { "deepmerge": "^4.2.2", "escape-string-regexp": "^4.0.0", "htmlparser2": "^12.0.0", "is-plain-object": "^5.0.0", "launder": "^1.7.1", "parse-srcset": "^1.0.2", "postcss": "^8.3.11" } }, "sha512-PGtEkc9cbnedU3s9TmzDbpsZ8w086g/0Q8k8/oIO1NLNU3i5k9yn835CrjJSajp1KMmkisbO1qPXxNKO3welAg=="],
"sax": ["sax@1.6.1", "", {}, "sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q=="],
"semver": ["semver@7.7.4", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA=="],
@@ -857,6 +871,8 @@
"sirv": ["sirv@3.0.2", "", { "dependencies": { "@polka/url": "1.0.0-next.29", "mrmime": "2.0.1", "totalist": "3.0.1" } }, "sha512-2wcC/oGxHis/BoHkkPwldgiPSYcpZK3JU28WoMVv55yHJgcZ8rlXvuG9iZggz+sU1d4bRgIGASwyWqjxu3FM0g=="],
"sitemap": ["sitemap@9.0.1", "", { "dependencies": { "@types/node": "^24.9.2", "@types/sax": "^1.2.1", "arg": "^5.0.0", "sax": "^1.4.1" }, "bin": { "sitemap": "dist/esm/cli.js" } }, "sha512-S6hzjGJSG3d6if0YoF5kTyeRJvia6FSTBroE5fQ0bu1QNxyJqhhinfUsXi9fH3MgtXODWvwo2BDyQSnhPQ88uQ=="],
"sorcery": ["sorcery@1.0.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "1.5.5", "minimist": "1.2.8", "tiny-glob": "0.2.9" }, "bin": { "sorcery": "bin/sorcery" } }, "sha512-5ay9oJE+7sNmhzl3YNG18jEEEf4AOQCM/FAqR5wMmzqd1FtRorFbJXn3w3SKOhbiQaVgHM+Q1lszZspjri7bpA=="],
"source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
@@ -933,6 +949,8 @@
"word-wrap": ["word-wrap@1.2.5", "", {}, "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA=="],
"xml-js": ["xml-js@1.6.11", "", { "dependencies": { "sax": "^1.2.4" }, "bin": { "xml-js": "./bin/cli.js" } }, "sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g=="],
"xtend": ["xtend@4.0.2", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="],
"yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
@@ -963,6 +981,8 @@
"@prisma/instrumentation/@opentelemetry/instrumentation": ["@opentelemetry/instrumentation@0.207.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.207.0", "import-in-the-middle": "2.0.6", "require-in-the-middle": "8.0.1" }, "peerDependencies": { "@opentelemetry/api": "1.9.1" } }, "sha512-y6eeli9+TLKnznrR8AZlQMSJT7wILpXH+6EYq5Vf/4Ao+huI7EedxQHwRgVUOMLFbe7VFDvHJrX9/f4lcwnJsA=="],
"@types/sax/@types/node": ["@types/node@24.13.6", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-SGrw/h3KPFshy3OE6ZL53LMBG5vGQQ8/gIpiqz/kRZhPJ7HgwCEs8LBuNtWLa8dvGZVpSF7+Bf+c11HUrCb/yg=="],
"@typescript-eslint/eslint-plugin/ignore": ["ignore@7.0.5", "", {}, "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg=="],
"@typescript-eslint/parser/@typescript-eslint/types": ["@typescript-eslint/types@8.59.1", "", {}, "sha512-ZDCjgccSdYPw5Bxh+my4Z0lJU96ZDN7jbBzvmEn0FZx3RtU1C7VWl6NbDx94bwY3V5YsgwRzJPOgeY2Q/nLG8A=="],
@@ -997,6 +1017,10 @@
"path-scurry/lru-cache": ["lru-cache@11.2.7", "", {}, "sha512-aY/R+aEsRelme17KGQa/1ZSIpLpNYYrhcrepKTZgE+W3WM16YMCaPwOHLHsmopZHELU0Ojin1lPVxKR0MihncA=="],
"sanitize-html/htmlparser2": ["htmlparser2@12.0.0", "", { "dependencies": { "domelementtype": "^3.0.0", "domhandler": "^6.0.0", "domutils": "^4.0.2", "entities": "^8.0.0" } }, "sha512-Tz7u1i95/g2x2jz81+x0FBVhBhY5aRTvD3tXXdFaljuNdzDLJ8UGNRrTcj2cgQvAg3iW/h77Fz15nLW0L0CrZw=="],
"sitemap/@types/node": ["@types/node@24.13.6", "", { "dependencies": { "undici-types": "~7.18.0" } }, "sha512-SGrw/h3KPFshy3OE6ZL53LMBG5vGQQ8/gIpiqz/kRZhPJ7HgwCEs8LBuNtWLa8dvGZVpSF7+Bf+c11HUrCb/yg=="],
"svelte-eslint-parser/postcss-selector-parser": ["postcss-selector-parser@7.1.1", "", { "dependencies": { "cssesc": "3.0.0", "util-deprecate": "1.0.2" } }, "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg=="],
"svelte-sonner/runed": ["runed@0.28.0", "", { "dependencies": { "esm-env": "1.2.2" }, "peerDependencies": { "svelte": "5.55.5" } }, "sha512-k2xx7RuO9hWcdd9f+8JoBeqWtYrm5CALfgpkg2YDB80ds/QE4w0qqu34A7fqiAwiBBSBQOid7TLxwxVC27ymWQ=="],
@@ -1015,16 +1039,30 @@
"@prisma/instrumentation/@opentelemetry/instrumentation/import-in-the-middle": ["import-in-the-middle@2.0.6", "", { "dependencies": { "acorn": "8.16.0", "acorn-import-attributes": "1.9.5", "cjs-module-lexer": "2.2.0", "module-details-from-path": "1.0.4" } }, "sha512-3vZV3jX0XRFW3EJDTwzWoZa+RH1b8eTTx6YOCjglrLyPuepwoBti1k3L2dKwdCUrnVEfc5CuRuGstaC/uQJJaw=="],
"@types/sax/@types/node/undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
"@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["brace-expansion@5.0.5", "", { "dependencies": { "balanced-match": "4.0.4" } }, "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ=="],
"glob/minimatch/brace-expansion": ["brace-expansion@5.0.5", "", { "dependencies": { "balanced-match": "4.0.4" } }, "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ=="],
"mode-watcher/svelte-toolbelt/runed": ["runed@0.23.4", "", { "dependencies": { "esm-env": "1.2.2" }, "peerDependencies": { "svelte": "5.55.5" } }, "sha512-9q8oUiBYeXIDLWNK5DfCWlkL0EW3oGbk845VdKlPeia28l751VpfesaB/+7pI6rnbx1I6rqoZ2fZxptOJLxILA=="],
"sanitize-html/htmlparser2/domelementtype": ["domelementtype@3.0.0", "", {}, "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg=="],
"sanitize-html/htmlparser2/domhandler": ["domhandler@6.0.1", "", { "dependencies": { "domelementtype": "^3.0.0" } }, "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg=="],
"sanitize-html/htmlparser2/domutils": ["domutils@4.0.2", "", { "dependencies": { "dom-serializer": "^3.0.0", "domelementtype": "^3.0.0", "domhandler": "^6.0.0" } }, "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA=="],
"sanitize-html/htmlparser2/entities": ["entities@8.1.0", "", {}, "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA=="],
"sitemap/@types/node/undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
"@fastify/otel/minimatch/brace-expansion/balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
"@typescript-eslint/typescript-estree/minimatch/brace-expansion/balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
"glob/minimatch/brace-expansion/balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="],
"sanitize-html/htmlparser2/domutils/dom-serializer": ["dom-serializer@3.1.1", "", { "dependencies": { "domelementtype": "^3.0.0", "domhandler": "^6.0.0", "entities": "^8.0.0" } }, "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw=="],
}
}
+3 -1
View File
@@ -40,6 +40,7 @@
"eslint-config-prettier": "10.1.8",
"eslint-plugin-simple-import-sort": "13.0.0",
"eslint-plugin-svelte": "3.17.1",
"feed": "6.0.0",
"globals": "17.5.0",
"highlight.js": "11.11.1",
"markdown-it": "14.1.1",
@@ -48,7 +49,8 @@
"prettier": "3.8.3",
"prettier-plugin-svelte": "3.5.1",
"prettier-plugin-tailwindcss": "0.7.2",
"sanitize-html": "2.17.3",
"sanitize-html": "2.17.7",
"sitemap": "9.0.1",
"svelte": "5.55.5",
"svelte-adapter-bun": "1.0.1",
"svelte-check": "4.4.6",
@@ -1,15 +1,4 @@
<script module lang="ts">
export const selfIntroductionLines = [
'大家好,我是 Squid 魷魚',
'身為一位軟體工程師',
'平常最喜歡埋首於程式碼的世界',
'鑽研各種新奇有趣的技術',
'在這裡',
'我會分享我的技術筆記、開發心得',
'還有各式各樣實用工具的評測與介紹',
'一起探索數位世界的無限可能吧!',
];
export interface StructuredDataArticleProps {
type: 'BlogPosting';
url: URL;
@@ -39,6 +28,7 @@
<script lang="ts">
import { Environment } from '$lib/environment';
import { Strings } from '$lib/strings';
/* eslint-disable svelte/no-at-html-tags */
@@ -106,7 +96,7 @@
url: Environment.APP_BASE_URL,
image: new URL('favicon.svg', Environment.APP_BASE_URL).href,
jobTitle: 'Software Engineer',
description: selfIntroductionLines.join(','),
description: Strings.SELF_INTRODUCTION_LINES.join(','),
alumniOf: {
'@type': 'EducationalOrganization',
name: 'National Central University',
+12
View File
@@ -45,6 +45,8 @@ import { GetAllPostsUseCase } from '$lib/post/application/useCase/getAllPostsUse
import { GetPostUseCase } from '$lib/post/application/useCase/getPostUseCase';
import { UpdatePostUseCase } from '$lib/post/application/useCase/updatePostUseCase';
import { PostApiServiceImpl } from '$lib/post/framework/api/postApiServiceImpl';
import { PostPagesListedStore } from '$lib/seo/adapter/presenter/postPagesListedStore';
import { ListPostPagesUseCase } from '$lib/seo/application/useCase/listPostPagesUseCase';
export class Container {
private useCases: UseCases;
@@ -95,6 +97,10 @@ export class Container {
return new PostUpdatedStore(this.useCases.updatePostUseCase);
}
createPostPagesListedStore(): PostPagesListedStore {
return new PostPagesListedStore(this.useCases.listPostPagesUseCase);
}
createLabelsListedStore(initialData?: readonly LabelViewModel[]): LabelsListedStore {
return new LabelsListedStore(this.useCases.getAllLabelsUseCase, initialData);
}
@@ -190,6 +196,7 @@ class UseCases {
private _getPostUseCase?: GetPostUseCase;
private _createPostUseCase?: CreatePostUseCase;
private _updatePostUseCase?: UpdatePostUseCase;
private _listPostPagesUseCase?: ListPostPagesUseCase;
private _getAllLabelsUseCase?: GetAllLabelsUseCase;
private _getLabelUseCase?: GetLabelUseCase;
private _createLabelUseCase?: CreateLabelUseCase;
@@ -244,6 +251,11 @@ class UseCases {
return this._updatePostUseCase;
}
get listPostPagesUseCase(): ListPostPagesUseCase {
this._listPostPagesUseCase ??= new ListPostPagesUseCase(this.getAllPostsUseCase);
return this._listPostPagesUseCase;
}
get getAllLabelsUseCase(): GetAllLabelsUseCase {
this._getAllLabelsUseCase ??= new GetAllLabelsUseCase(this.repositories.labelRepository);
return this._getAllLabelsUseCase;
@@ -1,18 +1,17 @@
<script lang="ts">
import generateTitle from '$lib/common/framework/ui/generateTitle';
import OpenGraph from '$lib/common/framework/ui/OpenGraph.svelte';
import StructuredData, {
selfIntroductionLines,
} from '$lib/common/framework/ui/StructuredData.svelte';
import StructuredData from '$lib/common/framework/ui/StructuredData.svelte';
import { Environment } from '$lib/environment';
import Motto from '$lib/home/framework/ui/Motto.svelte';
import Terminal from '$lib/home/framework/ui/Terminal.svelte';
import TitleScreen from '$lib/home/framework/ui/TitleScreen.svelte';
import { Strings } from '$lib/strings';
</script>
<svelte:head>
<title>{generateTitle()}</title>
<meta name="description" content={selfIntroductionLines.join(',')} />
<meta name="description" content={Strings.SELF_INTRODUCTION_LINES.join(',')} />
</svelte:head>
<StructuredData
@@ -23,7 +22,7 @@
<OpenGraph
title="首頁"
description={selfIntroductionLines.join(',')}
description={Strings.SELF_INTRODUCTION_LINES.join(',')}
url={new URL('', Environment.APP_BASE_URL)}
image={new URL('favicon.svg', Environment.APP_BASE_URL)}
labels={[]}
@@ -2,11 +2,11 @@
import { onDestroy, onMount } from 'svelte';
import { cn } from '$lib/common/framework/components/utils';
import { selfIntroductionLines } from '$lib/common/framework/ui/StructuredData.svelte';
import TerminalLastLine from '$lib/home/framework/ui/TerminalLastLine.svelte';
import TerminalNormalLine from '$lib/home/framework/ui/TerminalNormalLine.svelte';
import { Strings } from '$lib/strings';
const lines = selfIntroductionLines;
const lines = Strings.SELF_INTRODUCTION_LINES;
let isReady: boolean = $state(false);
let currentIndex: number = $state(0);
@@ -9,8 +9,11 @@ export const postInfoResponseSchema = z.object({
title: z.string(),
description: z.string(),
preview_image_url: z.string().nullable(),
preview_image_mime_type: z.string().nullable(),
preview_image_size: z.int().nullable(),
labels: z.array(labelResponseSchema),
published_time: z.iso.datetime({ offset: true }).nullable(),
updated_time: z.iso.datetime({ offset: true }).nullable(),
});
export class PostInfoResponseDto {
@@ -19,8 +22,11 @@ export class PostInfoResponseDto {
readonly title: string;
readonly description: string;
readonly previewImageUrl: string | null;
readonly previewImageMimeType: string | null;
readonly previewImageSize: number | null;
readonly labels: readonly LabelResponseDto[];
readonly publishedTime: Date | null;
readonly updatedTime: Date | null;
private constructor(props: {
id: number;
@@ -28,16 +34,22 @@ export class PostInfoResponseDto {
title: string;
description: string;
previewImageUrl: string | null;
previewImageMimeType: string | null;
previewImageSize: number | null;
labels: LabelResponseDto[];
publishedTime: Date | null;
updatedTime: Date | null;
}) {
this.id = props.id;
this.semanticId = props.semanticId;
this.title = props.title;
this.description = props.description;
this.previewImageUrl = props.previewImageUrl;
this.previewImageMimeType = props.previewImageMimeType;
this.previewImageSize = props.previewImageSize;
this.labels = props.labels;
this.publishedTime = props.publishedTime;
this.updatedTime = props.updatedTime;
}
static fromJson(json: unknown): PostInfoResponseDto {
@@ -48,14 +60,22 @@ export class PostInfoResponseDto {
published_time = new Date(parsedJson.published_time);
}
let updated_time: Date | null = null;
if (parsedJson.updated_time !== null) {
updated_time = new Date(parsedJson.updated_time);
}
return new PostInfoResponseDto({
id: parsedJson.id,
semanticId: parsedJson.semantic_id,
title: parsedJson.title,
description: parsedJson.description,
previewImageUrl: parsedJson.preview_image_url,
previewImageMimeType: parsedJson.preview_image_mime_type,
previewImageSize: parsedJson.preview_image_size,
labels: parsedJson.labels.map((label) => LabelResponseDto.fromJson(label)),
publishedTime: published_time,
updatedTime: updated_time,
});
}
@@ -66,8 +86,11 @@ export class PostInfoResponseDto {
title: this.title,
description: this.description,
previewImageUrl: this.previewImageUrl,
previewImageMimeType: this.previewImageMimeType,
previewImageSize: this.previewImageSize,
labels: this.labels.map((label) => label.toEntity()),
publishedTime: this.publishedTime,
updatedTime: this.updatedTime,
});
}
}
@@ -6,8 +6,11 @@ export class PostInfo {
readonly title: string;
readonly description: string;
readonly previewImageUrl: string | null;
readonly previewImageMimeType: string | null;
readonly previewImageSize: number | null;
readonly labels: readonly Label[];
readonly publishedTime: Date | null;
readonly updatedTime: Date | null;
constructor(props: {
id: number;
@@ -15,15 +18,21 @@ export class PostInfo {
title: string;
description: string;
previewImageUrl: string | null;
previewImageMimeType: string | null;
previewImageSize: number | null;
labels: readonly Label[];
publishedTime: Date | null;
updatedTime: Date | null;
}) {
this.id = props.id;
this.semanticId = props.semanticId;
this.title = props.title;
this.description = props.description;
this.previewImageUrl = props.previewImageUrl;
this.previewImageMimeType = props.previewImageMimeType;
this.previewImageSize = props.previewImageSize;
this.labels = props.labels;
this.publishedTime = props.publishedTime;
this.updatedTime = props.updatedTime;
}
}
@@ -0,0 +1,38 @@
import { captureException } from '@sentry/sveltekit';
import { get, writable } from 'svelte/store';
import { AsyncState } from '$lib/common/adapter/presenter/asyncState';
import type { BaseStore } from '$lib/common/adapter/presenter/baseStore';
import type { ListPostPagesUseCase } from '$lib/seo/application/useCase/listPostPagesUseCase';
import type { PostPage } from '$lib/seo/domain/entity/postPage';
type PostPagesState = AsyncState<readonly PostPage[]>;
export class PostPagesListedStore implements BaseStore<PostPagesState> {
private readonly state = writable<PostPagesState>(AsyncState.idle<readonly PostPage[]>(null));
constructor(private readonly listPostPagesUseCase: ListPostPagesUseCase) {}
get subscribe() {
return this.state.subscribe;
}
get trigger() {
return () => this.loadPostPages();
}
private async loadPostPages(): Promise<PostPagesState> {
this.state.set(AsyncState.loading(get(this.state).data));
let result: PostPagesState;
try {
result = AsyncState.success(await this.listPostPagesUseCase.execute());
} catch (e) {
result = AsyncState.error(e, get(this.state).data);
captureException(e);
}
this.state.set(result);
return result;
}
}
@@ -0,0 +1,43 @@
import { resolve } from '$app/paths';
import { Environment } from '$lib/environment';
import type { GetAllPostsUseCase } from '$lib/post/application/useCase/getAllPostsUseCase';
import type { PostInfo } from '$lib/post/domain/entity/postInfo';
import { PostPage } from '$lib/seo/domain/entity/postPage';
/**
* Turns published posts into their public pages. The public URL of a post is a frontend
* routing concern, so this is the single place that knows how to build it. Both sitemap.xml
* and feed.xml consume the result, so the link is never duplicated in the backend or docs.
*/
export class ListPostPagesUseCase {
constructor(private readonly getAllPostsUseCase: GetAllPostsUseCase) {}
async execute(): Promise<readonly PostPage[]> {
const posts = await this.getAllPostsUseCase.execute(false);
return posts.flatMap((post) => {
const { publishedTime } = post;
if (publishedTime === null) {
return [];
}
return [ListPostPagesUseCase.toPostPage(post, publishedTime)];
});
}
private static toPostPage(post: PostInfo, publishedTime: Date): PostPage {
return new PostPage({
url: new URL(resolve('/post/[id]', { id: post.semanticId }), Environment.APP_BASE_URL),
semanticId: post.semanticId,
title: post.title,
description: post.description,
publishedTime,
lastModified: post.updatedTime ?? publishedTime,
previewImageUrl: post.previewImageUrl
? new URL(post.previewImageUrl, Environment.APP_BASE_URL)
: null,
previewImageMimeType: post.previewImageMimeType,
previewImageSize: post.previewImageSize,
categories: post.labels.map((label) => label.name),
});
}
}
@@ -0,0 +1,45 @@
/**
* A published post projected as a public page. It is the shared unit consumed by both
* sitemap.xml and feed.xml. Non-post pages (home page, post list, terms, ...) are only
* relevant to the sitemap and are handled where the sitemap is built.
*/
export class PostPage {
readonly url: URL;
/**
* The post's stable semantic id. It identifies the post in feed.xml, so it must not change
* when the public URL scheme changes, or subscribers would re-surface every post as new.
*/
readonly semanticId: string;
readonly title: string;
readonly description: string;
readonly publishedTime: Date;
readonly lastModified: Date;
readonly previewImageUrl: URL | null;
readonly previewImageMimeType: string | null;
readonly previewImageSize: number | null;
readonly categories: readonly string[];
constructor(props: {
url: URL;
semanticId: string;
title: string;
description: string;
publishedTime: Date;
lastModified: Date;
previewImageUrl: URL | null;
previewImageMimeType: string | null;
previewImageSize: number | null;
categories: readonly string[];
}) {
this.url = props.url;
this.semanticId = props.semanticId;
this.title = props.title;
this.description = props.description;
this.publishedTime = props.publishedTime;
this.lastModified = props.lastModified;
this.previewImageUrl = props.previewImageUrl;
this.previewImageMimeType = props.previewImageMimeType;
this.previewImageSize = props.previewImageSize;
this.categories = props.categories;
}
}
@@ -0,0 +1,18 @@
import { resolve } from '$app/paths';
import { Environment } from '$lib/environment';
import { TERMS_DOCUMENTS } from '$lib/terms/framework/termsDocuments';
/**
* The public, non-post pages of the site. They are only relevant to the sitemap (never to
* the feed), and only the frontend knows these routes, so the list lives here rather than
* in the domain.
*/
export function listStaticSitePageUrls(): readonly string[] {
const paths = [
resolve('/'),
resolve('/post'),
...TERMS_DOCUMENTS.map((document) => resolve('/terms/[name]', { name: document.pathname })),
];
return paths.map((path) => new URL(path, Environment.APP_BASE_URL).href);
}
@@ -0,0 +1,68 @@
import { Feed, type Item } from 'feed';
import { Environment } from '$lib/environment';
import { Links } from '$lib/links';
import type { PostPage } from '$lib/seo/domain/entity/postPage';
import { Strings } from '$lib/strings';
const FEED_LANGUAGE = 'zh-TW';
/**
* How many of the most recent posts the feed advertises. A feed is a rolling window over
* the newest content, unlike the sitemap which lists every page.
*/
const FEED_ITEM_LIMIT = 20;
/**
* Builds feed.xml from the published posts. Server-only: it must never be imported from
* client code.
*/
export function buildFeedDocument(postPages: readonly PostPage[]): string {
const feed = new Feed({
title: Strings.APP_NAME,
id: Environment.APP_BASE_URL,
link: Environment.APP_BASE_URL,
description: Strings.SITE_DESCRIPTION,
language: FEED_LANGUAGE,
generator: false,
feed: Links.RSS.href,
updated: new Date(),
});
const latestPostPages = [...postPages]
.sort((a, b) => b.publishedTime.getTime() - a.publishedTime.getTime())
.slice(0, FEED_ITEM_LIMIT);
for (const page of latestPostPages) {
const item: Item = {
title: page.title,
// The guid is the post's stable semantic id rather than its URL, so changing the URL
// scheme does not make every post reappear as unread for existing subscribers. The
// package renders it as <guid isPermaLink="false">.
guid: page.semanticId,
link: page.url.href,
description: page.description,
date: page.lastModified,
published: page.publishedTime,
category: page.categories.map((name) => ({ name })),
};
// RSS enclosures require a MIME type and a length, both of which the backend
// provides for uploaded preview images.
if (
page.previewImageUrl &&
page.previewImageMimeType !== null &&
page.previewImageSize !== null
) {
item.image = {
url: page.previewImageUrl.href,
type: page.previewImageMimeType,
length: page.previewImageSize,
};
}
feed.addItem(item);
}
return feed.rss2();
}
@@ -0,0 +1,25 @@
import { SitemapStream, streamToPromise } from 'sitemap';
import type { PostPage } from '$lib/seo/domain/entity/postPage';
import { listStaticSitePageUrls } from '$lib/seo/framework/site/staticSitePages';
/**
* Builds sitemap.xml from the published posts plus the static pages. Server-only: it pulls
* in a Node stream implementation, so it must never be imported from client code.
*/
export async function buildSitemapDocument(postPages: readonly PostPage[]): Promise<string> {
const stream = new SitemapStream();
for (const url of listStaticSitePageUrls()) {
stream.write({ url });
}
for (const page of postPages) {
stream.write({ url: page.url.href, lastmod: page.lastModified.toISOString() });
}
stream.end();
const sitemap = await streamToPromise(stream);
return sitemap.toString();
}
+11
View File
@@ -27,11 +27,22 @@ export abstract class Strings {
static readonly SEARCH_POST_HINT: string =
'輸入文章內容片段,或直接提出具體問題,系統將會以 AI(向量比對)搜尋相關的文章內容,搜尋結果根據相關性排序。';
static readonly SEARCH_UNAVAILABLE: string = '搜尋暫時無法使用,請稍後再試';
static readonly SELF_INTRODUCTION_LINES: readonly string[] = [
'大家好,我是 Squid 魷魚',
'身為一位軟體工程師',
'平常最喜歡埋首於程式碼的世界',
'鑽研各種新奇有趣的技術',
'在這裡',
'我會分享我的技術筆記、開發心得',
'還有各式各樣實用工具的評測與介紹',
'一起探索數位世界的無限可能吧!',
];
static readonly SHARE: string = 'Share';
static readonly SHARE_TO_EMAIL: string = 'Email';
static readonly SHARE_TO_FACEBOOK: string = 'Facebook';
static readonly SHARE_TO_LINKEDIN: string = 'LinkedIn';
static readonly SHARE_TO_X: string = 'X';
static readonly SITE_DESCRIPTION: string = Strings.SELF_INTRODUCTION_LINES.join(',');
static readonly TOC: string = '章節目錄';
static readonly YOUTUBE_CHANNEL: string = 'YouTube Channel';
}
@@ -0,0 +1,11 @@
import { Strings } from '$lib/strings';
export interface TermsDocument {
readonly pathname: string;
readonly title: string;
}
export const TERMS_DOCUMENTS: readonly TermsDocument[] = [
{ pathname: 'privacy-policy', title: Strings.PRIVACY_POLICY },
{ pathname: 'ai-usage-policy', title: Strings.AI_USAGE_POLICY },
];
+28
View File
@@ -0,0 +1,28 @@
import { error } from '@sveltejs/kit';
import { buildFeedDocument } from '$lib/seo/framework/xml/feedDocument';
import type { RequestHandler } from './$types';
// The document is derived from database state, so it is generated on demand and cached
// briefly rather than baked into the image at build time.
const CACHE_CONTROL = 'public, max-age=300';
export const GET: RequestHandler = async ({ locals }) => {
const store = locals.container.createPostPagesListedStore();
const state = await store.trigger();
const postPages = state.data;
if (state.isError() || postPages === null) {
error(500, 'Failed to generate the feed');
}
const body = buildFeedDocument(postPages);
return new Response(body, {
headers: {
'Content-Type': 'application/rss+xml; charset=utf-8',
'Cache-Control': CACHE_CONTROL,
},
});
};
@@ -0,0 +1,28 @@
import { error } from '@sveltejs/kit';
import { buildSitemapDocument } from '$lib/seo/framework/xml/sitemapDocument';
import type { RequestHandler } from './$types';
// The document is derived from database state, so it is generated on demand and cached
// briefly rather than baked into the image at build time.
const CACHE_CONTROL = 'public, max-age=300';
export const GET: RequestHandler = async ({ locals }) => {
const store = locals.container.createPostPagesListedStore();
const state = await store.trigger();
const postPages = state.data;
if (state.isError() || postPages === null) {
error(500, 'Failed to generate the sitemap');
}
const body = await buildSitemapDocument(postPages);
return new Response(body, {
headers: {
'Content-Type': 'application/xml; charset=utf-8',
'Cache-Control': CACHE_CONTROL,
},
});
};
+1 -11
View File
@@ -1,19 +1,9 @@
import { error } from '@sveltejs/kit';
import { Strings } from '$lib/strings';
import { TERMS_DOCUMENTS } from '$lib/terms/framework/termsDocuments';
import type { PageLoad } from './$types';
interface TermsDocument {
pathname: string;
title: string;
}
const TERMS_DOCUMENTS: TermsDocument[] = [
{ pathname: 'privacy-policy', title: Strings.PRIVACY_POLICY },
{ pathname: 'ai-usage-policy', title: Strings.AI_USAGE_POLICY },
];
export const load: PageLoad = async ({ fetch, params }) => {
const { name } = params;
if (!TERMS_DOCUMENTS.map((doc) => doc.pathname).includes(name)) {
+2
View File
@@ -1,3 +1,5 @@
User-agent: *
Allow: /
Disallow: /dashboard/
Sitemap: /sitemap.xml
+1 -1
View File
@@ -3,4 +3,4 @@
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
cd "$SCRIPT_DIR/../../backend"
cargo check && cargo test
cargo check && cargo clippy && cargo test
-12
View File
@@ -1,12 +0,0 @@
SERVER_BASE_URL=https://example.com/
# Database Configuration
DATABASE_HOST=127.0.0.1
DATABASE_PORT=5432
DATABASE_USER=postgres
DATABASE_PASSWORD=
DATABASE_NAME=postgres
# RSS Feed Configuration
RSS_LANGUAGE=zh-TW
RSS_OUTPUT_FILE=feed.xml
-218
View File
@@ -1,218 +0,0 @@
*.xml
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[codz]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py.cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
# Pipfile.lock
# UV
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# uv.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
# poetry.lock
# poetry.toml
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
# pdm.lock
# pdm.toml
.pdm-python
.pdm-build/
# pixi
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
# pixi.lock
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
# in the .venv directory. It is recommended not to include this directory in version control.
.pixi
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# Redis
*.rdb
*.aof
*.pid
# RabbitMQ
mnesia/
rabbitmq/
rabbitmq-data/
# ActiveMQ
activemq-data/
# SageMath parsed files
*.sage.py
# Environments
.env
.envrc
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
# .idea/
# Abstra
# Abstra is an AI-powered process automation framework.
# Ignore directories containing user credentials, local state, and settings.
# Learn more at https://abstra.io/docs
.abstra/
# Visual Studio Code
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
# and can be added to the global gitignore or merged into this file. However, if you prefer,
# you could uncomment the following to ignore the entire vscode folder
# .vscode/
# Ruff stuff:
.ruff_cache/
# PyPI configuration file
.pypirc
# Marimo
marimo/_static/
marimo/_lsp/
__marimo__/
# Streamlit
.streamlit/secrets.toml
-34
View File
@@ -1,34 +0,0 @@
FROM python:3.14-slim AS base
FROM base AS dependencies
# build-essential is only needed if a dependency has no prebuilt wheel and has to be
# compiled from source. Confining it to this stage keeps it out of the final image.
RUN apt-get update && apt-get install -y build-essential && \
apt-get clean && rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt .
RUN python -m venv .venv && \
. .venv/bin/activate && \
pip install --no-cache-dir -r requirements.txt
FROM base
WORKDIR /app
COPY --from=dependencies /app/.venv .venv
# Only the script is needed at runtime: feed.xml is bind-mounted, not baked in.
COPY generate_rss.py ./
ENV PATH="/app/.venv/bin:$PATH"
# Set default environment variables
ENV DATABASE_HOST=127.0.0.1
ENV DATABASE_PORT=5432
ENV DATABASE_USER=postgres
ENV DATABASE_PASSWORD=""
ENV DATABASE_NAME=postgres
ENV RSS_LANGUAGE="zh-TW"
ENV RSS_OUTPUT_FILE="feed.xml"
ENV SERVER_BASE_URL="https://example.com/"
CMD ["sleep", "infinity"]
-60
View File
@@ -1,60 +0,0 @@
# Toolbox Scripts
This directory contains utility scripts for the blog application.
## RSS Generator (`generate_rss.py`)
This script connects to the PostgreSQL database, fetches published posts, and generates an RSS 2.0 feed XML file.
### Usage
The toolbox container is designed to run in the background (sleeping). You can execute the generation script inside the running container.
#### 1. Volume Configuration
To make the generated `feed.xml` accessible to your web server or host machine, you need to mount a volume when starting the container.
For example, if you want the feed to be generated at `/var/www/blog/feed.xml` on the host machine:
1. Ensure the file exists on the host (e.g., `touch /var/www/blog/feed.xml`), otherwise it might be created as a directory.
2. Mount the host file directly to the path inside the container.
3. Set the `RSS_OUTPUT_FILE` environment variable to point to that internal path.
```bash
podman run -d \
--name blog-toolbox \
--env-file .env \
-v /var/www/blog/feed.xml:/app/feed.xml \
-e RSS_OUTPUT_FILE=/app/feed.xml \
blog-toolbox-image
```
#### 2. Generate RSS Feed
Run the following command to generate the RSS feed:
```bash
podman exec -it blog-toolbox python generate_rss.py
```
### Environment Variables
The script relies on the following environment variables:
| Variable | Description | Default |
|----------|-------------|---------|
| `DATABASE_HOST` | PostgreSQL database host | `127.0.0.1` |
| `DATABASE_PORT` | PostgreSQL database port | `5432` |
| `DATABASE_NAME` | Database name | `postgres` |
| `DATABASE_USER` | Database user | `postgres` |
| `DATABASE_PASSWORD` | Database password | (empty) |
| `SERVER_BASE_URL` | Base URL of the blog. Used for generating links and fetching site title/description. | `http://localhost/` |
| `RSS_LANGUAGE` | Language code for the RSS feed | `zh-TW` |
| `RSS_OUTPUT_FILE` | Absolute path where the XML file will be written inside the container | `feed.xml` |
### Features
- **Dynamic Metadata**: Fetches the site title and description from the `SERVER_BASE_URL` HTML head.
- **Preview Images**: Includes preview images in the feed as `<enclosure>` elements, automatically detecting the correct MIME type and content length from HTTP response headers.
- **Semantic IDs**: Uses semantic IDs for permanent links and GUIDs.
- **UTF-8 Support**: Properly handles Chinese and other Unicode characters in titles and descriptions.
-283
View File
@@ -1,283 +0,0 @@
import os
from datetime import datetime, timezone
from typing import Any
from xml.dom import minidom
from xml.etree.ElementTree import Element, SubElement, tostring
import psycopg2
import requests
from dotenv import load_dotenv
from psycopg2.extras import RealDictCursor
load_dotenv()
# Database configuration
DB_CONFIG = {
"host": os.getenv("DATABASE_HOST", "127.0.0.1"),
"port": os.getenv("DATABASE_PORT", "5432"),
"database": os.getenv("DATABASE_NAME", "postgres"),
"user": os.getenv("DATABASE_USER", "postgres"),
"password": os.getenv("DATABASE_PASSWORD", ""),
}
# RSS feed configuration
RSS_CONFIG = {
"language": os.getenv("RSS_LANGUAGE", "zh-TW"),
"output_file": os.getenv("RSS_OUTPUT_FILE", "feed.xml"),
}
SERVER_BASE_URL = os.getenv("SERVER_BASE_URL", "http://localhost/")
def get_site_metadata() -> dict[str, str]:
"""
Get site title and description from SERVER_BASE_URL HTML head
"""
try:
response = requests.get(SERVER_BASE_URL, timeout=10)
response.raise_for_status()
# Ensure proper encoding for Chinese characters
response.encoding = response.apparent_encoding or "utf-8"
html_content = response.text
# Extract title
title = "My Blog"
title_start = html_content.find("<title>")
if title_start != -1:
title_start += len("<title>")
title_end = html_content.find("</title>", title_start)
if title_end != -1:
title = html_content[title_start:title_end].strip()
# Extract description from meta tag
description = "Blog RSS Feed"
desc_start = html_content.find('<meta name="description"')
if desc_start != -1:
content_start = html_content.find('content="', desc_start)
if content_start != -1:
content_start += len('content="')
content_end = html_content.find('"', content_start)
if content_end != -1:
description = html_content[content_start:content_end].strip()
return {"title": title, "description": description}
except Exception as e:
print(f"Warning: Failed to fetch site metadata: {e}")
return {"title": "My Blog", "description": "Blog RSS Feed"}
def get_content_type_and_length(url: str) -> tuple[str, int]:
"""
Get content type and content length from URL response headers
Returns: (content_type, content_length)
"""
try:
# Try HEAD request first
response = requests.head(url, timeout=5, allow_redirects=True)
content_type = response.headers.get("Content-Type", "")
content_length = int(response.headers.get("Content-Length", 0))
# If we got a valid image content type, return it
if content_type and content_type.startswith("image/"):
return content_type.split(";")[0].strip(), content_length
# If HEAD request didn't work, try GET with stream
response = requests.get(url, timeout=5, allow_redirects=True, stream=True)
content_type = response.headers.get("Content-Type", "")
content_length = int(response.headers.get("Content-Length", 0))
response.close() # Close the connection immediately
if content_type:
return content_type.split(";")[0].strip(), content_length
return "image/jpeg", content_length # Default fallback
except Exception:
# Default to image/jpeg if request fails
return "image/jpeg", 0
def get_posts_from_db() -> list[dict[str, Any]]:
conn = None
try:
conn = psycopg2.connect(
dsn=f"host={DB_CONFIG['host']} port={DB_CONFIG['port']} dbname={DB_CONFIG['database']} user={DB_CONFIG['user']} password={DB_CONFIG['password']}"
)
cursor = conn.cursor(cursor_factory=RealDictCursor)
# Fetch published posts with labels
query = """
SELECT
p.id,
p.semantic_id,
p.preview_image_url,
p.title,
p.description,
p.published_time,
p.updated_time,
ARRAY_AGG(l.name ORDER BY pl."order") FILTER (WHERE l.id IS NOT NULL) AS labels
FROM
post p
LEFT JOIN
post_label pl ON p.id = pl.post_id
LEFT JOIN
label l ON pl.label_id = l.id AND l.deleted_time IS NULL
WHERE
p.deleted_time IS NULL
AND p.published_time IS NOT NULL
GROUP BY
p.id, p.semantic_id, p.title, p.description, p.content, p.published_time, p.updated_time
ORDER BY
p.published_time DESC
LIMIT 20
"""
cursor.execute(query)
posts = cursor.fetchall()
cursor.close()
return [dict(post) for post in posts]
except Exception as e:
print(f"Database error: {e}")
return []
finally:
if conn:
conn.close()
def generate_rss_feed(posts: list[dict[str, Any]]) -> str:
"""
Generate RSS 2.0 format XML
"""
# Get site metadata from homepage
site_metadata = get_site_metadata()
# Create root element
rss = Element(
"rss",
version="2.0",
attrib={
"xmlns:atom": "http://www.w3.org/2005/Atom",
"xmlns:content": "http://purl.org/rss/1.0/modules/content/",
},
)
channel = SubElement(rss, "channel")
# Channel basic information
SubElement(channel, "title").text = site_metadata["title"]
SubElement(channel, "link").text = SERVER_BASE_URL
SubElement(channel, "description").text = site_metadata["description"]
SubElement(channel, "language").text = RSS_CONFIG["language"]
SubElement(channel, "lastBuildDate").text = datetime.now(tz=timezone.utc).strftime(
"%a, %d %b %Y %H:%M:%S +0000"
)
# Atom self link
SubElement(
channel,
"atom:link",
attrib={
"href": f"{SERVER_BASE_URL}feed.xml",
"rel": "self",
"type": "application/rss+xml",
},
)
# Create item for each post
for post in posts:
item = SubElement(channel, "item")
# Title
SubElement(item, "title").text = post.get("title", "Untitled")
# Post link (using semantic_id)
post_link = f"{SERVER_BASE_URL}post/{post.get('semantic_id', '')}"
SubElement(item, "link").text = post_link
# GUID uses semantic_id as unique identifier
sementic_id = post.get("semantic_id", "")
SubElement(item, "guid", attrib={"isPermaLink": "false"}).text = sementic_id
# Description or content
description = post.get("description", "")
SubElement(item, "description").text = description
# Preview image (enclosure)
if "preview_image_url" in post and post["preview_image_url"]:
preview_url = post["preview_image_url"]
# If it's a relative URL, make it absolute
if not preview_url.startswith(("http://", "https://")):
preview_url = f"{SERVER_BASE_URL.rstrip('/')}/{preview_url.lstrip('/')}"
# Get content type and length from response headers
content_type, content_length = get_content_type_and_length(preview_url)
enclosure_attrs = {
"url": preview_url,
"type": content_type,
}
# Add length attribute if available
if content_length > 0:
enclosure_attrs["length"] = str(content_length)
SubElement(item, "enclosure", attrib=enclosure_attrs)
# Publish date
if "published_time" in post and post["published_time"]:
pub_date = post["published_time"]
if isinstance(pub_date, datetime):
SubElement(item, "pubDate").text = pub_date.strftime(
"%a, %d %b %Y %H:%M:%S +0000"
)
# Labels/categories
if "labels" in post and post["labels"]:
for label in post["labels"]:
if label: # Filter empty values
SubElement(item, "category").text = label
# Format XML
xml_string = tostring(rss, encoding="unicode")
dom = minidom.parseString(xml_string)
pretty_xml = dom.toprettyxml(indent=" ", encoding="UTF-8").decode("utf-8")
# Remove extra blank lines
lines = [line for line in pretty_xml.split("\n") if line.strip()]
return "\n".join(lines)
def save_rss_feed(xml_content: str, output_file: str):
"""
Save RSS feed to file
"""
try:
with open(output_file, "w", encoding="utf-8") as f:
f.write(xml_content)
print(f"RSS feed successfully generated: {output_file}")
except Exception as e:
print(f"Error saving RSS feed: {e}")
def main():
print("Fetching posts from database...")
posts = get_posts_from_db()
if not posts:
print("No posts found or database error occurred.")
return
print(f"Found {len(posts)} posts. Generating RSS feed...")
xml_content = generate_rss_feed(posts)
output_file = RSS_CONFIG["output_file"]
save_rss_feed(xml_content, output_file)
if __name__ == "__main__":
main()
-3
View File
@@ -1,3 +0,0 @@
python-dotenv==1.2.1
psycopg2-binary==2.9.11
requests==2.32.5