This commit is contained in:
2026-03-26 00:50:11 +01:00
parent 798552d16f
commit c61a5ff3c5
15 changed files with 1005 additions and 995 deletions
+46
View File
@@ -0,0 +1,46 @@
use axum::{
extract::State,
http::HeaderMap,
response::IntoResponse,
Json,
};
use std::{fs, sync::Arc};
use tracing::error;
use crate::{
auth::check_auth,
error::AppError,
models::SiteConfig,
AppState,
};
pub async fn get_config(State(state): State<Arc<AppState>>) -> impl IntoResponse {
let config_path = state.data_dir.join("config.json");
let config = fs::read_to_string(&config_path)
.ok()
.and_then(|c| serde_json::from_str::<SiteConfig>(&c).ok())
.unwrap_or_default();
Json(config)
}
pub async fn update_config(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
Json(payload): Json<SiteConfig>,
) -> Result<Json<SiteConfig>, AppError> {
check_auth(&headers, &state.admin_token)?;
let config_path = state.data_dir.join("config.json");
let config_str = serde_json::to_string_pretty(&payload).map_err(|e| {
error!("Serialization error: {}", e);
AppError::Internal("Serialization error".to_string(), Some(e.to_string()))
})?;
fs::write(&config_path, config_str).map_err(|e| {
error!("Write error for config: {}", e);
AppError::Internal("Write error".to_string(), Some(e.to_string()))
})?;
Ok(Json(payload))
}
+3
View File
@@ -0,0 +1,3 @@
pub mod config;
pub mod posts;
pub mod upload;
+105
View File
@@ -0,0 +1,105 @@
use axum::{
extract::{Path, State},
http::{HeaderMap, StatusCode},
response::IntoResponse,
Json,
};
use std::{fs, sync::Arc};
use tracing::{error, info, warn};
use crate::{
auth::check_auth,
error::AppError,
models::{CreatePostRequest, PostDetail, PostInfo},
AppState,
};
pub async fn create_post(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
Json(payload): Json<CreatePostRequest>,
) -> Result<Json<PostDetail>, AppError> {
check_auth(&headers, &state.admin_token)?;
if payload.slug.contains('/') || payload.slug.contains('\\') || payload.slug.contains("..") {
return Err(AppError::BadRequest("Invalid slug".to_string()));
}
let file_path = state.data_dir.join("posts").join(format!("{}.md", payload.slug));
fs::write(&file_path, &payload.content).map_err(|e| {
error!("Write error for post {}: {}", payload.slug, e);
AppError::Internal("Write error".to_string(), Some(e.to_string()))
})?;
info!("Post created/updated: {}", payload.slug);
Ok(Json(PostDetail {
slug: payload.slug,
content: payload.content,
}))
}
pub async fn delete_post(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
Path(slug): Path<String>,
) -> Result<StatusCode, AppError> {
check_auth(&headers, &state.admin_token)?;
let file_path = state.data_dir.join("posts").join(format!("{}.md", slug));
info!("Attempting to delete post at: {:?}", file_path);
if !file_path.exists() {
warn!("Post not found for deletion: {}", slug);
return Err(AppError::NotFound("Post not found".to_string()));
}
fs::remove_file(file_path).map_err(|e| {
error!("Delete error for post {}: {}", slug, e);
AppError::Internal("Delete error".to_string(), Some(e.to_string()))
})?;
info!("Post deleted: {}", slug);
Ok(StatusCode::NO_CONTENT)
}
pub async fn list_posts(State(state): State<Arc<AppState>>) -> impl IntoResponse {
let posts_dir = state.data_dir.join("posts");
let mut posts = Vec::new();
if let Ok(entries) = fs::read_dir(posts_dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) == Some("md") {
if let Some(slug) = path.file_stem().and_then(|s| s.to_str()) {
let mut excerpt = String::new();
if let Ok(content) = fs::read_to_string(&path) {
let clean_content = content.replace("#", "").replace("\n", " ");
excerpt = clean_content.chars().take(200).collect::<String>();
if clean_content.len() > 200 {
excerpt.push_str("...");
}
}
posts.push(PostInfo {
slug: slug.to_string(),
excerpt: excerpt.trim().to_string(),
});
}
}
}
}
Json(posts)
}
pub async fn get_post(
State(state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<Json<PostDetail>, AppError> {
let file_path = state.data_dir.join("posts").join(format!("{}.md", slug));
match fs::read_to_string(&file_path) {
Ok(content) => Ok(Json(PostDetail { slug, content })),
Err(_) => Err(AppError::NotFound("Post not found".to_string())),
}
}
+105
View File
@@ -0,0 +1,105 @@
use axum::{
extract::{Multipart, State},
http::HeaderMap,
response::IntoResponse,
Json,
};
use std::{fs, sync::Arc};
use tracing::{error, info, warn};
use crate::{
auth::check_auth,
error::AppError,
models::{FileInfo, UploadResponse},
AppState,
};
pub async fn list_uploads(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
) -> Result<Json<Vec<FileInfo>>, AppError> {
check_auth(&headers, &state.admin_token)?;
let uploads_dir = state.data_dir.join("uploads");
let mut files = Vec::new();
if let Ok(entries) = fs::read_dir(uploads_dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() {
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
files.push(FileInfo {
name: name.to_string(),
url: format!("/uploads/{}", name),
});
}
}
}
}
Ok(Json(files))
}
pub async fn upload_file(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
mut multipart: Multipart,
) -> Result<Json<UploadResponse>, AppError> {
check_auth(&headers, &state.admin_token)?;
info!("Upload requested");
while let Ok(Some(field)) = multipart.next_field().await {
let file_name = match field.file_name() {
Some(name) => name.to_string(),
None => continue,
};
info!("Processing upload for: {}", file_name);
let slugified_name = slug::slugify(&file_name);
let extension = std::path::Path::new(&file_name)
.extension()
.and_then(|e| e.to_str())
.unwrap_or("");
let final_name = if !extension.is_empty() {
format!("{}.{}", slugified_name, extension)
} else {
slugified_name
};
let uploads_dir = state.data_dir.join("uploads");
let file_path = uploads_dir.join(&final_name);
let final_path = if file_path.exists() {
let timestamp = chrono::Utc::now().timestamp();
uploads_dir.join(format!("{}_{}", timestamp, final_name))
} else {
file_path
};
let final_name_str = final_path.file_name().unwrap().to_str().unwrap().to_string();
let data = match field.bytes().await {
Ok(bytes) => bytes,
Err(e) => {
error!("Failed to read multipart bytes: {}", e);
return Err(AppError::BadRequest(format!("Read error: {}", e)));
}
};
if let Err(e) = fs::write(&final_path, &data) {
error!("Failed to write file to {:?}: {}", final_path, e);
return Err(AppError::Internal("Write error".to_string(), Some(e.to_string())));
}
info!("File uploaded successfully to {:?}", final_path);
return Ok(Json(UploadResponse {
url: format!("/uploads/{}", final_name_str),
}));
}
warn!("Upload failed: no file found in multipart stream");
Err(AppError::BadRequest("No file found".to_string()))
}