feat: implement Search Session API and complete API integrations
Test / test (push) Has been cancelled
Test / build (push) Has been cancelled

Core Features:
- Add search_sessions and search_messages tables (SQLite)
- Implement 7 CRUD API endpoints for search sessions
- Add auto-cleanup logic (24h + 50 sessions limit)
- Add user isolation (per-user SQLite)
- Add performance optimizations (indexes + pagination)

Additional APIs:
- Fix MBE models API (404 -> empty list)
- Add Settings API (GET/POST /api/v2/settings)
- Add Settings Validation API (POST /api/v2/settings/validate)
- Add Admin Token Authentication (/api/v2/admin/login, verify)

Documentation:
- Add Search Session API implementation report
- Add Settings API implementation guide
- Add Validation API report
- Add Admin API guide
- Add MBE API fix documentation

Tests: All endpoints tested and working
Refs: docs/SEARCH_SESSION_API_REPORT.md
This commit is contained in:
Warren
2026-10-27 04:19:06 +08:00
parent 8073ed0752
commit b1d06bfab6
14 changed files with 4030 additions and 0 deletions
+31
View File
@@ -0,0 +1,31 @@
use axum::{
extract::Json,
http::StatusCode,
response::{IntoResponse, Result as AxumResult},
};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MbeModelsResponse {
pub models: Vec<MbeModel>,
#[serde(skip_serializing_if = "Option::is_none")]
pub default: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MbeModel {
pub id: String,
pub dir: String,
pub name: String,
}
pub async fn get_mbe_models_handler() -> AxumResult<impl IntoResponse> {
// Return empty list by default
// MBE (MarkBase Engine) is an optional standalone service
let response = MbeModelsResponse {
models: vec![],
default: None,
};
Ok((StatusCode::OK, Json(response)))
}
+3
View File
@@ -2,3 +2,6 @@ pub mod admin;
pub mod config;
pub mod handlers;
pub mod docs;
pub mod settings;
pub mod mbe;
pub mod search_sessions;
+865
View File
@@ -0,0 +1,865 @@
use axum::{
extract::{Path, Query, State},
http::HeaderMap,
http::StatusCode,
response::{IntoResponse, Json},
};
use rusqlite::Connection;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use crate::server::AppState;
// === Data Structures ===
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchSession {
pub id: String,
#[serde(skip_serializing)]
pub user_id: String,
pub title: String,
pub mode: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub message_count: Option<i64>,
pub created_at: String,
pub updated_at: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchMessage {
pub id: String,
#[serde(skip_serializing)]
pub session_id: String,
pub role: String,
pub content: String,
pub results: String,
pub mode: String,
pub created_at: String,
}
// === Request/Response Structures ===
#[derive(Debug, Deserialize)]
pub struct CreateSessionRequest {
#[serde(default = "default_session_title")]
pub title: String,
#[serde(default = "default_session_mode")]
pub mode: String,
}
fn default_session_title() -> String {
"未命名搜尋".to_string()
}
fn default_session_mode() -> String {
"keyword".to_string()
}
#[derive(Debug, Deserialize)]
pub struct UpdateSessionRequest {
pub title: String,
}
#[derive(Debug, Deserialize)]
pub struct CreateMessageRequest {
pub role: String,
#[serde(default)]
pub content: String,
#[serde(default)]
pub mode: String,
#[serde(default)]
pub results: String,
}
#[derive(Debug, Deserialize)]
pub struct UpdateMessageRequest {
#[serde(default)]
pub role: String,
#[serde(default)]
pub content: String,
#[serde(default)]
pub results: String,
}
#[derive(Debug, Deserialize)]
pub struct ListSessionsQuery {
#[serde(default = "default_limit")]
pub limit: u32,
#[serde(default)]
pub offset: u32,
}
fn default_limit() -> u32 {
30
}
#[derive(Debug, Serialize)]
pub struct ListSessionsResponse {
pub success: bool,
pub total: i64,
pub sessions: Vec<SearchSession>,
}
#[derive(Debug, Serialize)]
pub struct CreateSessionResponse {
pub success: bool,
pub session: SearchSession,
}
#[derive(Debug, Serialize)]
pub struct UpdateSessionResponse {
pub success: bool,
pub message: String,
}
#[derive(Debug, Serialize)]
pub struct DeleteSessionResponse {
pub success: bool,
pub message: String,
}
#[derive(Debug, Serialize)]
pub struct ListMessagesResponse {
pub success: bool,
pub messages: Vec<SearchMessage>,
}
#[derive(Debug, Serialize)]
pub struct CreateMessageResponse {
pub success: bool,
pub message: SearchMessage,
}
#[derive(Debug, Serialize)]
pub struct UpdateMessageResponse {
pub success: bool,
pub message: String,
}
#[derive(Debug, Serialize)]
pub struct ErrorResponse {
pub success: bool,
pub error: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
}
// === Helper Functions ===
fn verify_admin_token(
state: &AppState,
headers: &HeaderMap,
) -> Result<String, (StatusCode, Json<ErrorResponse>)> {
let auth_header = headers
.get("Authorization")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "));
match auth_header {
Some(token) => {
if let Some(session) = state.auth.verify_admin_token(token) {
Ok(session.username)
} else {
Err((
StatusCode::UNAUTHORIZED,
Json(ErrorResponse {
success: false,
error: "Invalid admin token".to_string(),
code: Some("UNAUTHORIZED".to_string()),
}),
))
}
}
None => Err((
StatusCode::UNAUTHORIZED,
Json(ErrorResponse {
success: false,
error: "Missing Authorization header".to_string(),
code: Some("UNAUTHORIZED".to_string()),
}),
)),
}
}
fn generate_id() -> String {
format!("sess_{}", uuid::Uuid::new_v4())
}
fn generate_message_id() -> String {
format!("msg_{}", uuid::Uuid::new_v4())
}
fn cleanup_old_sessions(conn: &Connection, user_id: &str) -> Result<(), rusqlite::Error> {
// 1. Delete sessions older than 24 hours with default title
conn.execute(
"DELETE FROM search_sessions
WHERE user_id = ?1
AND title = '未命名搜尋'
AND datetime(created_at) < datetime('now', '-24 hours')",
[user_id]
)?;
// 2. Check session count
let count: i64 = conn.query_row(
"SELECT COUNT(*) FROM search_sessions WHERE user_id = ?1",
[user_id],
|r| r.get(0)
)?;
// 3. Delete oldest sessions if exceeds limit
if count > 50 {
let excess = count - 50;
conn.execute(
"DELETE FROM search_sessions
WHERE rowid IN (
SELECT rowid FROM search_sessions
WHERE user_id = ?1
AND title = '未命名搜尋'
ORDER BY updated_at ASC
LIMIT ?2
)",
rusqlite::params![user_id, excess]
)?;
}
Ok(())
}
// === API Handlers ===
pub async fn list_sessions(
State(state): State<AppState>,
headers: HeaderMap,
Query(query): Query<ListSessionsQuery>,
) -> impl IntoResponse {
let user_id = match verify_admin_token(&state, &headers) {
Ok(uid) => uid,
Err(resp) => return resp.into_response(),
};
let conn = match crate::db::get_or_create_user_db(&user_id) {
Ok(c) => c,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Database error: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response();
}
};
// Get total count
let total: i64 = match conn.query_row(
"SELECT COUNT(*) FROM search_sessions WHERE user_id = ?1",
[&user_id],
|r| r.get(0),
) {
Ok(t) => t,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Database error: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response();
}
};
// Get sessions with message count
let mut stmt = match conn.prepare(
"SELECT s.id, s.title, s.mode, s.created_at, s.updated_at,
(SELECT COUNT(*) FROM search_messages WHERE session_id = s.id) as message_count
FROM search_sessions s
WHERE s.user_id = ?1
ORDER BY s.updated_at DESC
LIMIT ?2 OFFSET ?3"
) {
Ok(s) => s,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Database error: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response();
}
};
let sessions: Vec<SearchSession> = match stmt.query_map(
rusqlite::params![&user_id, query.limit, query.offset],
|row| {
Ok(SearchSession {
id: row.get(0)?,
user_id: user_id.clone(),
title: row.get(1)?,
mode: row.get(2)?,
created_at: row.get(3)?,
updated_at: row.get(4)?,
message_count: Some(row.get(5)?),
})
},
) {
Ok(rows) => rows.filter_map(|r| r.ok()).collect(),
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Database error: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response();
}
};
(StatusCode::OK, Json(ListSessionsResponse {
success: true,
total,
sessions,
})).into_response()
}
pub async fn create_session(
State(state): State<AppState>,
headers: HeaderMap,
Json(body): Json<CreateSessionRequest>,
) -> impl IntoResponse {
let user_id = match verify_admin_token(&state, &headers) {
Ok(uid) => uid,
Err(resp) => return resp.into_response(),
};
let conn = match crate::db::get_or_create_user_db(&user_id) {
Ok(c) => c,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Database error: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response();
}
};
// Cleanup old sessions before creating new one
if let Err(e) = cleanup_old_sessions(&conn, &user_id) {
log::warn!("Failed to cleanup old sessions: {}", e);
}
let session_id = generate_id();
let now = chrono::Utc::now().to_rfc3339();
match conn.execute(
"INSERT INTO search_sessions (id, user_id, title, mode, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
rusqlite::params![
&session_id,
&user_id,
&body.title,
&body.mode,
&now,
&now
],
) {
Ok(_) => {
let session = SearchSession {
id: session_id,
user_id,
title: body.title,
mode: body.mode,
message_count: Some(0),
created_at: now.clone(),
updated_at: now,
};
(StatusCode::CREATED, Json(CreateSessionResponse {
success: true,
session,
})).into_response()
}
Err(e) => {
(StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Failed to create session: {}", e),
code: Some("DATABASE_ERROR".to_string()),
})).into_response()
}
}
}
pub async fn update_session(
State(state): State<AppState>,
headers: HeaderMap,
Path(session_id): Path<String>,
Json(body): Json<UpdateSessionRequest>,
) -> impl IntoResponse {
let user_id = match verify_admin_token(&state, &headers) {
Ok(uid) => uid,
Err(resp) => return resp.into_response(),
};
let conn = match crate::db::get_or_create_user_db(&user_id) {
Ok(c) => c,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Database error: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response();
}
};
let now = chrono::Utc::now().to_rfc3339();
match conn.execute(
"UPDATE search_sessions SET title = ?1, updated_at = ?2
WHERE id = ?3 AND user_id = ?4",
rusqlite::params![&body.title, &now, &session_id, &user_id],
) {
Ok(rows_affected) => {
if rows_affected == 0 {
(
StatusCode::NOT_FOUND,
Json(ErrorResponse {
success: false,
error: "Session not found".to_string(),
code: Some("SESSION_NOT_FOUND".to_string()),
}),
)
.into_response()
} else {
(
StatusCode::OK,
Json(UpdateSessionResponse {
success: true,
message: "Session updated".to_string(),
}),
)
.into_response()
}
}
Err(e) => {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Failed to update session: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response()
}
}
}
pub async fn delete_session(
State(state): State<AppState>,
headers: HeaderMap,
Path(session_id): Path<String>,
) -> impl IntoResponse {
let user_id = match verify_admin_token(&state, &headers) {
Ok(uid) => uid,
Err(resp) => return resp.into_response(),
};
let conn = match crate::db::get_or_create_user_db(&user_id) {
Ok(c) => c,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Database error: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response();
}
};
match conn.execute(
"DELETE FROM search_sessions WHERE id = ?1 AND user_id = ?2",
rusqlite::params![&session_id, &user_id],
) {
Ok(rows_affected) => {
if rows_affected == 0 {
(
StatusCode::NOT_FOUND,
Json(ErrorResponse {
success: false,
error: "Session not found".to_string(),
code: Some("SESSION_NOT_FOUND".to_string()),
}),
)
.into_response()
} else {
(
StatusCode::OK,
Json(DeleteSessionResponse {
success: true,
message: "Session deleted".to_string(),
}),
)
.into_response()
}
}
Err(e) => {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Failed to delete session: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response()
}
}
}
pub async fn list_messages(
State(state): State<AppState>,
headers: HeaderMap,
Path(session_id): Path<String>,
) -> impl IntoResponse {
let user_id = match verify_admin_token(&state, &headers) {
Ok(uid) => uid,
Err(resp) => return resp.into_response(),
};
let conn = match crate::db::get_or_create_user_db(&user_id) {
Ok(c) => c,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Database error: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response();
}
};
// Verify session exists and belongs to user
let exists: bool = match conn.query_row(
"SELECT EXISTS(SELECT 1 FROM search_sessions WHERE id = ?1 AND user_id = ?2)",
rusqlite::params![&session_id, &user_id],
|r| r.get(0),
) {
Ok(e) => e,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Database error: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response();
}
};
if !exists {
return (
StatusCode::NOT_FOUND,
Json(ErrorResponse {
success: false,
error: "Session not found".to_string(),
code: Some("SESSION_NOT_FOUND".to_string()),
}),
)
.into_response();
}
let mut stmt = match conn.prepare(
"SELECT id, session_id, role, content, results, mode, created_at
FROM search_messages
WHERE session_id = ?1
ORDER BY created_at ASC"
) {
Ok(s) => s,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Database error: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response();
}
};
let messages: Vec<SearchMessage> = match stmt.query_map(
[&session_id],
|row| {
Ok(SearchMessage {
id: row.get(0)?,
session_id: row.get(1)?,
role: row.get(2)?,
content: row.get(3)?,
results: row.get(4)?,
mode: row.get(5)?,
created_at: row.get(6)?,
})
},
) {
Ok(rows) => rows.filter_map(|r| r.ok()).collect(),
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Database error: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response();
}
};
(StatusCode::OK, Json(ListMessagesResponse {
success: true,
messages,
})).into_response()
}
pub async fn create_message(
State(state): State<AppState>,
headers: HeaderMap,
Path(session_id): Path<String>,
Json(body): Json<CreateMessageRequest>,
) -> impl IntoResponse {
let user_id = match verify_admin_token(&state, &headers) {
Ok(uid) => uid,
Err(resp) => return resp.into_response(),
};
let conn = match crate::db::get_or_create_user_db(&user_id) {
Ok(c) => c,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Database error: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response();
}
};
// Verify session exists and belongs to user
let exists: bool = match conn.query_row(
"SELECT EXISTS(SELECT 1 FROM search_sessions WHERE id = ?1 AND user_id = ?2)",
rusqlite::params![&session_id, &user_id],
|r| r.get(0),
) {
Ok(e) => e,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Database error: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response();
}
};
if !exists {
return (
StatusCode::NOT_FOUND,
Json(ErrorResponse {
success: false,
error: "Session not found".to_string(),
code: Some("SESSION_NOT_FOUND".to_string()),
}),
)
.into_response();
}
let message_id = generate_message_id();
let now = chrono::Utc::now().to_rfc3339();
match conn.execute(
"INSERT INTO search_messages (id, session_id, role, content, results, mode, created_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
rusqlite::params![
&message_id,
&session_id,
&body.role,
&body.content,
&body.results,
&body.mode,
&now
],
) {
Ok(_) => {
// Update session's updated_at timestamp
let _ = conn.execute(
"UPDATE search_sessions SET updated_at = ?1 WHERE id = ?2",
rusqlite::params![&now, &session_id],
);
let message = SearchMessage {
id: message_id,
session_id,
role: body.role,
content: body.content,
results: body.results,
mode: body.mode,
created_at: now,
};
(StatusCode::CREATED, Json(CreateMessageResponse {
success: true,
message,
})).into_response()
}
Err(e) => {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Failed to create message: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response()
}
}
}
pub async fn update_message(
State(state): State<AppState>,
headers: HeaderMap,
Path((session_id, message_id)): Path<(String, String)>,
Json(body): Json<UpdateMessageRequest>,
) -> impl IntoResponse {
let user_id = match verify_admin_token(&state, &headers) {
Ok(uid) => uid,
Err(resp) => return resp.into_response(),
};
let conn = match crate::db::get_or_create_user_db(&user_id) {
Ok(c) => c,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Database error: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response();
}
};
// Verify session exists and belongs to user
let exists: bool = match conn.query_row(
"SELECT EXISTS(SELECT 1 FROM search_sessions WHERE id = ?1 AND user_id = ?2)",
rusqlite::params![&session_id, &user_id],
|r| r.get(0),
) {
Ok(e) => e,
Err(e) => {
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Database error: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response();
}
};
if !exists {
return (
StatusCode::NOT_FOUND,
Json(ErrorResponse {
success: false,
error: "Session not found".to_string(),
code: Some("SESSION_NOT_FOUND".to_string()),
}),
)
.into_response();
}
let now = chrono::Utc::now().to_rfc3339();
match conn.execute(
"UPDATE search_messages SET role = ?1, content = ?2, results = ?3
WHERE id = ?4 AND session_id = ?5",
rusqlite::params![&body.role, &body.content, &body.results, &message_id, &session_id],
) {
Ok(rows_affected) => {
if rows_affected == 0 {
(
StatusCode::NOT_FOUND,
Json(ErrorResponse {
success: false,
error: "Message not found".to_string(),
code: Some("MESSAGE_NOT_FOUND".to_string()),
}),
)
.into_response()
} else {
// Update session's updated_at timestamp
let _ = conn.execute(
"UPDATE search_sessions SET updated_at = ?1 WHERE id = ?2",
rusqlite::params![&now, &session_id],
);
(
StatusCode::OK,
Json(UpdateMessageResponse {
success: true,
message: "Message updated".to_string(),
}),
)
.into_response()
}
}
Err(e) => {
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
success: false,
error: format!("Failed to update message: {}", e),
code: Some("DATABASE_ERROR".to_string()),
}),
)
.into_response()
}
}
}
+361
View File
@@ -0,0 +1,361 @@
use axum::{
extract::Json,
http::StatusCode,
response::{IntoResponse, Result as AxumResult},
};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SettingsResponse {
pub success: bool,
pub settings: Settings,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Settings {
pub server: ServerSettings,
pub database: DatabaseSettings,
pub webdav: WebDAVSettings,
pub s3: S3Settings,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerSettings {
pub upload_path: String,
pub port: u16,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseSettings {
#[serde(rename = "type")]
pub db_type: String,
pub path: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WebDAVSettings {
pub enabled: bool,
pub parent_path: String,
pub versioning: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct S3Settings {
pub enabled: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateSettingsRequest {
#[serde(default)]
pub server: Option<ServerSettingsUpdate>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerSettingsUpdate {
pub upload_path: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateSettingsResponse {
pub success: bool,
pub message: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidateSettingsRequest {
#[serde(default)]
pub server: Option<ServerSettingsUpdate>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidateSettingsResponse {
pub success: bool,
pub valid: bool,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub details: Option<ValidationDetails>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationDetails {
pub path_exists: bool,
pub path_readable: bool,
pub path_writable: bool,
pub path_is_directory: bool,
pub absolute_path: String,
}
pub async fn get_settings_handler() -> AxumResult<impl IntoResponse> {
let config_path = std::path::Path::new("config/markbase.toml");
let upload_path = if config_path.exists() {
match crate::config::MarkBaseConfig::load(config_path) {
Ok(config) => config.server.upload_path.clone(),
Err(_) => "/Users/accusys/momentry/var/sftpgo/data".to_string(),
}
} else {
"/Users/accusys/momentry/var/sftpgo/data".to_string()
};
let webdav_parent = std::env::var("MB_WEBDAV_PARENT")
.unwrap_or_else(|_| upload_path.clone());
let settings = Settings {
server: ServerSettings {
upload_path: upload_path.clone(),
port: 11438,
},
database: DatabaseSettings {
db_type: "sqlite".to_string(),
path: "data/auth.sqlite".to_string(),
},
webdav: WebDAVSettings {
enabled: true,
parent_path: webdav_parent,
versioning: true,
},
s3: S3Settings {
enabled: false,
},
};
Ok((
StatusCode::OK,
Json(SettingsResponse {
success: true,
settings,
}),
))
}
pub async fn update_settings_handler(
Json(request): Json<UpdateSettingsRequest>,
) -> AxumResult<impl IntoResponse> {
let config_path = std::path::Path::new("config/markbase.toml");
let mut config = if config_path.exists() {
match crate::config::MarkBaseConfig::load(config_path) {
Ok(c) => c,
Err(e) => {
log::error!("Failed to load config: {}", e);
return Ok((
StatusCode::INTERNAL_SERVER_ERROR,
Json(UpdateSettingsResponse {
success: false,
message: format!("Failed to load config: {}", e),
}),
));
}
}
} else {
crate::config::MarkBaseConfig::default_config()
};
if let Some(server_update) = request.server {
if let Some(new_upload_path) = server_update.upload_path {
let path = std::path::Path::new(&new_upload_path);
if !path.exists() {
return Ok((
StatusCode::BAD_REQUEST,
Json(UpdateSettingsResponse {
success: false,
message: format!("Path does not exist: {}", new_upload_path),
}),
));
}
config.server.upload_path = new_upload_path.clone();
match config.save(config_path) {
Ok(_) => {
log::info!("Settings updated: upload_path = {}", new_upload_path);
return Ok((
StatusCode::OK,
Json(UpdateSettingsResponse {
success: true,
message: "Settings updated successfully".to_string(),
}),
));
}
Err(e) => {
log::error!("Failed to save config: {}", e);
return Ok((
StatusCode::INTERNAL_SERVER_ERROR,
Json(UpdateSettingsResponse {
success: false,
message: format!("Failed to save config: {}", e),
}),
));
}
}
}
}
Ok((
StatusCode::OK,
Json(UpdateSettingsResponse {
success: true,
message: "No changes made".to_string(),
}),
))
}
pub async fn validate_settings_handler(
Json(request): Json<ValidateSettingsRequest>,
) -> AxumResult<impl IntoResponse> {
if let Some(server_update) = request.server {
if let Some(upload_path) = server_update.upload_path {
let path = std::path::Path::new(&upload_path);
// 1. Check path format
if upload_path.is_empty() {
return Ok((
StatusCode::BAD_REQUEST,
Json(ValidateSettingsResponse {
success: true,
valid: false,
message: "Path cannot be empty".to_string(),
details: None,
}),
));
}
// 2. Check if path contains invalid characters
let invalid_chars = ['\0', '\n', '\r'];
if upload_path.chars().any(|c| invalid_chars.contains(&c)) {
return Ok((
StatusCode::BAD_REQUEST,
Json(ValidateSettingsResponse {
success: true,
valid: false,
message: "Path contains invalid characters".to_string(),
details: None,
}),
));
}
// 3. Get absolute path
let absolute_path = if path.is_absolute() {
upload_path.clone()
} else {
match std::fs::canonicalize(path) {
Ok(abs) => abs.to_string_lossy().to_string(),
Err(_) => {
// Path doesn't exist yet, try to resolve relative path
let current_dir = std::env::current_dir()
.unwrap_or_else(|_| std::path::PathBuf::from("/"));
current_dir.join(path).to_string_lossy().to_string()
}
}
};
// 4. Check path existence
let path_exists = path.exists();
let path_is_directory = path.exists() && path.is_dir();
// 5. Check permissions (if path exists)
let (path_readable, path_writable) = if path_exists {
let readable = std::fs::read_dir(path).is_ok();
// Check if we can write to the directory by checking metadata
let writable = match std::fs::metadata(path) {
Ok(metadata) => {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = metadata.permissions().mode();
// Check if user has write permission (0o200)
(mode & 0o200) != 0
}
#[cfg(not(unix))]
{
// Fallback: try to create a temp file
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path.join(".markbase_write_test"))
.and_then(|f| {
drop(f);
std::fs::remove_file(path.join(".markbase_write_test"))
})
.is_ok()
}
}
Err(_) => false,
};
(readable, writable)
} else {
// Try to check parent directory permissions
let parent = path.parent();
if let Some(parent_path) = parent {
if parent_path.exists() {
match std::fs::metadata(parent_path) {
Ok(metadata) => {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = metadata.permissions().mode();
((mode & 0o200) != 0, (mode & 0o200) != 0)
}
#[cfg(not(unix))]
{
(true, true) // Assume writable on non-Unix systems
}
}
Err(_) => (false, false),
}
} else {
(false, false)
}
} else {
(false, false)
}
};
// 6. Build response
let details = ValidationDetails {
path_exists,
path_readable,
path_writable,
path_is_directory,
absolute_path,
};
// 7. Determine validation result
let valid = path_exists && path_is_directory && path_readable && path_writable;
let message = if !path_exists {
format!("Path does not exist: {}", upload_path)
} else if !path_is_directory {
format!("Path is not a directory: {}", upload_path)
} else if !path_readable {
format!("Path is not readable: {}", upload_path)
} else if !path_writable {
format!("Path is not writable: {}", upload_path)
} else {
format!("Path is valid: {}", upload_path)
};
return Ok((
StatusCode::OK,
Json(ValidateSettingsResponse {
success: true,
valid,
message,
details: Some(details),
}),
));
}
}
Ok((
StatusCode::BAD_REQUEST,
Json(ValidateSettingsResponse {
success: false,
valid: false,
message: "No path provided for validation".to_string(),
details: None,
}),
))
}
+3
View File
@@ -0,0 +1,3 @@
pub mod schema;
pub use schema::*;
+58
View File
@@ -0,0 +1,58 @@
use anyhow::Result;
use rusqlite::Connection;
use std::path::PathBuf;
pub const SEARCH_SESSIONS_SCHEMA: &str = r#"
CREATE TABLE IF NOT EXISTS search_sessions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
title TEXT NOT NULL DEFAULT '未命名搜尋',
mode TEXT DEFAULT 'keyword',
created_at TEXT DEFAULT (datetime('now')),
updated_at TEXT DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_sessions_user ON search_sessions(user_id);
CREATE INDEX IF NOT EXISTS idx_sessions_updated ON search_sessions(user_id, updated_at DESC);
"#;
pub const SEARCH_MESSAGES_SCHEMA: &str = r#"
CREATE TABLE IF NOT EXISTS search_messages (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL REFERENCES search_sessions(id) ON DELETE CASCADE,
role TEXT NOT NULL,
content TEXT,
results TEXT,
mode TEXT DEFAULT 'keyword',
created_at TEXT DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_messages_session ON search_messages(session_id, created_at);
"#;
pub fn get_user_db_path(username: &str) -> PathBuf {
PathBuf::from("data/users").join(format!("{}.sqlite", username))
}
pub fn init_search_tables(conn: &Connection) -> Result<()> {
conn.execute_batch(&format!(
"{}; {}",
SEARCH_SESSIONS_SCHEMA, SEARCH_MESSAGES_SCHEMA
))?;
Ok(())
}
pub fn get_or_create_user_db(username: &str) -> Result<Connection> {
let db_path = get_user_db_path(username);
if !db_path.exists() {
if let Some(parent) = db_path.parent() {
std::fs::create_dir_all(parent)?;
}
}
let conn = Connection::open(&db_path)?;
init_search_tables(&conn)?;
Ok(conn)
}
+1
View File
@@ -12,6 +12,7 @@ pub mod download;
pub mod import_markdown;
pub mod myfiles;
pub mod provider;
pub mod db;
pub mod render;
pub mod rsync;
pub mod s3;
+11
View File
@@ -295,6 +295,17 @@ pub async fn run(port: u16, file: Option<String>, home: PathBuf) -> anyhow::Resu
.route("/api/v2/config/s3", get(crate::api::config::get_s3_config_handler))
.route("/api/v2/config/s3/edit", post(crate::api::config::edit_s3_config_handler))
.route("/api/v2/config/s3/validate", get(crate::api::config::validate_s3_config_handler))
// Settings API endpoints (public) - structured JSON for Studio integration
.route("/api/v2/settings", get(crate::api::settings::get_settings_handler))
.route("/api/v2/settings", post(crate::api::settings::update_settings_handler))
.route("/api/v2/settings/validate", post(crate::api::settings::validate_settings_handler))
// MBE API endpoints (optional service)
.route("/api/v2/mbe/models", get(crate::api::mbe::get_mbe_models_handler))
// Search Session API endpoints
.route("/api/v2/search-sessions", get(crate::api::search_sessions::list_sessions).post(crate::api::search_sessions::create_session))
.route("/api/v2/search-sessions/:id", put(crate::api::search_sessions::update_session).delete(crate::api::search_sessions::delete_session))
.route("/api/v2/search-sessions/:id/messages", get(crate::api::search_sessions::list_messages).post(crate::api::search_sessions::create_message))
.route("/api/v2/search-sessions/:id/messages/:msgId", patch(crate::api::search_sessions::update_message))
// .route("/api/v2/config/sftp", get(get_sftp_config_handler))
// .route("/api/v2/config/sftp/edit", post(edit_sftp_config_handler))
// .route("/api/v2/config/sftp/validate", get(validate_sftp_config_handler))