ext/web W7: finish network extension polish
Ship Cache-Control, 301 redirects, custom 404/500, sitemap/robots, and init unique/index so the web capability roadmap is complete for P0–P2. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
6808d56c9d
commit
323449c2c3
13 files changed
+920
-34
No files matched your search
@@ -183,6 +183,7 @@ pub fn init(url: &str, table: &str, fields: &Value) -> Result<Value, String> {
|
||||
}
|
||||
let mut parts = Vec::new();
|
||||
let mut has_pk = false;
|
||||
let mut index_sql = Vec::new();
|
||||
for c in arr {
|
||||
let name = c
|
||||
.get("name")
|
||||
@@ -204,6 +205,28 @@ pub fn init(url: &str, table: &str, fields: &Value) -> Result<Value, String> {
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(true);
|
||||
let unique = c
|
||||
.get("unique")
|
||||
.or_else(|| c.get("唯一"))
|
||||
.and_then(|v| match v {
|
||||
Value::Bool(b) => Some(*b),
|
||||
Value::String(s) => {
|
||||
Some(matches!(s.as_str(), "true" | "True" | "1" | "yes" | "是" | "唯一"))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(false);
|
||||
let index = c
|
||||
.get("index")
|
||||
.or_else(|| c.get("索引"))
|
||||
.and_then(|v| match v {
|
||||
Value::Bool(b) => Some(*b),
|
||||
Value::String(s) => {
|
||||
Some(matches!(s.as_str(), "true" | "True" | "1" | "yes" | "是" | "索引"))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(false);
|
||||
let mut col = format!("\"{name}\" {}", sql_type(&ty));
|
||||
if name == "id" && !has_pk {
|
||||
col.push_str(" PRIMARY KEY");
|
||||
@@ -214,7 +237,16 @@ pub fn init(url: &str, table: &str, fields: &Value) -> Result<Value, String> {
|
||||
} else if !nullable {
|
||||
col.push_str(" NOT NULL");
|
||||
}
|
||||
if unique && name != "id" {
|
||||
col.push_str(" UNIQUE");
|
||||
}
|
||||
parts.push(col);
|
||||
if (index || unique) && name != "id" {
|
||||
let kind = if unique { "UNIQUE " } else { "" };
|
||||
index_sql.push(format!(
|
||||
"CREATE {kind}INDEX IF NOT EXISTS \"idx_{table}_{name}\" ON \"{table}\" (\"{name}\")"
|
||||
));
|
||||
}
|
||||
}
|
||||
let sql = format!(
|
||||
"CREATE TABLE IF NOT EXISTS \"{table}\" ({})",
|
||||
@@ -223,6 +255,9 @@ pub fn init(url: &str, table: &str, fields: &Value) -> Result<Value, String> {
|
||||
let conn = pooled(url)?;
|
||||
let c = conn.lock().unwrap_or_else(|e| e.into_inner());
|
||||
c.execute_batch(&sql).map_err(|e| e.to_string())?;
|
||||
for stmt in index_sql {
|
||||
c.execute_batch(&stmt).map_err(|e| e.to_string())?;
|
||||
}
|
||||
Ok(json!({ "_type": "db_table", "name": table, "url": url }))
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ use crate::rate_limit;
|
||||
use crate::render;
|
||||
use crate::rss;
|
||||
use crate::session;
|
||||
use crate::sitemap;
|
||||
use crate::storage;
|
||||
use crate::upload;
|
||||
|
||||
@@ -54,6 +55,9 @@ pub struct AppState {
|
||||
cookie_secure: bool,
|
||||
upload_routes: HashMap<String, UploadRoute>,
|
||||
download_routes: HashMap<String, DownloadRoute>,
|
||||
/// Optional assembled pages for 404 / 500.
|
||||
page_404: Option<Value>,
|
||||
page_500: Option<Value>,
|
||||
}
|
||||
|
||||
fn collect_page_forms(
|
||||
@@ -95,6 +99,11 @@ pub fn listen(
|
||||
rss_routes: HashMap<String, Value>,
|
||||
upload_routes: HashMap<String, UploadRoute>,
|
||||
download_routes: HashMap<String, DownloadRoute>,
|
||||
redirects: HashMap<String, (String, bool)>,
|
||||
sitemap_routes: HashMap<String, Value>,
|
||||
robots_body: Option<String>,
|
||||
page_404: Option<Value>,
|
||||
page_500: Option<Value>,
|
||||
middleware: &Middleware,
|
||||
) -> Result<Value, String> {
|
||||
let mut form_owners = HashMap::new();
|
||||
@@ -120,6 +129,8 @@ pub fn listen(
|
||||
cookie_secure,
|
||||
upload_routes: upload_routes.clone(),
|
||||
download_routes: download_routes.clone(),
|
||||
page_404: page_404.clone(),
|
||||
page_500: page_500.clone(),
|
||||
});
|
||||
|
||||
let mut app = Router::new()
|
||||
@@ -267,6 +278,65 @@ pub fn listen(
|
||||
app = app.nest_service(&mount, svc);
|
||||
}
|
||||
|
||||
let mut redir_paths: Vec<String> = redirects.keys().cloned().collect();
|
||||
redir_paths.sort();
|
||||
for path in redir_paths {
|
||||
let (to, permanent) = redirects.get(&path).cloned().unwrap_or_default();
|
||||
app = app.route(
|
||||
&path,
|
||||
get(move || {
|
||||
let to = to.clone();
|
||||
let permanent = permanent;
|
||||
async move {
|
||||
// 301 for permanent (SEO), 307 for temporary — not axum's 308/307 defaults.
|
||||
let status = if permanent {
|
||||
StatusCode::MOVED_PERMANENTLY
|
||||
} else {
|
||||
StatusCode::TEMPORARY_REDIRECT
|
||||
};
|
||||
match HeaderValue::from_str(&to) {
|
||||
Ok(loc) => (status, [(header::LOCATION, loc)]).into_response(),
|
||||
Err(_) => Redirect::to(&to).into_response(),
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
let mut sm_paths: Vec<String> = sitemap_routes.keys().cloned().collect();
|
||||
sm_paths.sort();
|
||||
for path in sm_paths {
|
||||
let cfg = sitemap_routes.get(&path).cloned().unwrap_or_default();
|
||||
app = app.route(
|
||||
&path,
|
||||
get(move |State(st): State<Arc<AppState>>| {
|
||||
let cfg = cfg.clone();
|
||||
async move { sitemap_response(&st, &cfg) }
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(body) = robots_body {
|
||||
app = app.route(
|
||||
"/robots.txt",
|
||||
get(move || {
|
||||
let body = body.clone();
|
||||
async move {
|
||||
(
|
||||
[(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("text/plain; charset=utf-8"),
|
||||
)],
|
||||
body,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
app = app.fallback(get(fallback_404));
|
||||
|
||||
let app = crate::middleware::apply(app, middleware);
|
||||
let app = app.with_state(state);
|
||||
|
||||
@@ -1323,6 +1393,79 @@ fn esc(s: &str) -> String {
|
||||
.replace('>', ">")
|
||||
}
|
||||
|
||||
fn sitemap_response(st: &AppState, cfg: &Value) -> Response {
|
||||
let base = cfg
|
||||
.get("base")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let table = cfg.get("table").and_then(|v| v.as_str());
|
||||
let loc_col = cfg
|
||||
.get("loc")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("path");
|
||||
let limit = cfg
|
||||
.get("limit")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(1000);
|
||||
let mut items = cfg.get("items").cloned().unwrap_or(json!([]));
|
||||
if let (Some(url), Some(table)) = (st.db_url.as_deref(), table) {
|
||||
if let Ok(rows) = db::select_order(url, table, limit, None, None, None, None) {
|
||||
if let Some(arr) = rows.get("rows").cloned() {
|
||||
// Normalize loc column → loc
|
||||
if let Some(list) = arr.as_array() {
|
||||
let mut out = Vec::new();
|
||||
for row in list {
|
||||
let mut m = row.as_object().cloned().unwrap_or_default();
|
||||
if !m.contains_key("loc") {
|
||||
if let Some(v) = m.get(loc_col).cloned() {
|
||||
m.insert("loc".into(), v);
|
||||
}
|
||||
}
|
||||
out.push(Value::Object(m));
|
||||
}
|
||||
items = Value::Array(out);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let xml = sitemap::build_sitemap(base, &items);
|
||||
(
|
||||
[(
|
||||
header::CONTENT_TYPE,
|
||||
HeaderValue::from_static("application/xml; charset=utf-8"),
|
||||
)],
|
||||
xml,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
async fn fallback_404(State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap) -> Response {
|
||||
let (_, csrf, set_cookie) = resolve_session(&headers);
|
||||
let html = if let Some(ref page) = st.page_404 {
|
||||
render::render_page(page, st.db_url.as_deref(), Some(&csrf))
|
||||
} else {
|
||||
"<!doctype html><html><head><title>404</title></head><body><h1>404 Not Found</h1></body></html>"
|
||||
.to_string()
|
||||
};
|
||||
let mut resp = (StatusCode::NOT_FOUND, Html(html)).into_response();
|
||||
append_set_cookie(&mut resp, set_cookie);
|
||||
resp
|
||||
}
|
||||
|
||||
/// Render a custom 500 page when configured.
|
||||
#[allow(dead_code)]
|
||||
fn error_500(st: &AppState, csrf: Option<&str>, msg: &str) -> Response {
|
||||
let html = if let Some(ref page) = st.page_500 {
|
||||
render::render_page(page, st.db_url.as_deref(), csrf)
|
||||
} else {
|
||||
format!(
|
||||
"<!doctype html><html><head><title>500</title></head><body><h1>500</h1><p>{}</p></body></html>",
|
||||
esc(msg)
|
||||
)
|
||||
};
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, Html(html)).into_response()
|
||||
}
|
||||
|
||||
/// WebSocket server endpoint.
|
||||
/// - `echo`: reply each text frame to the same socket
|
||||
/// - `broadcast`: fan-out text frames to all sockets on this path
|
||||
|
||||
+186
-1
@@ -14,6 +14,7 @@ mod rate_limit;
|
||||
mod render;
|
||||
mod rss;
|
||||
mod session;
|
||||
mod sitemap;
|
||||
mod storage;
|
||||
mod table;
|
||||
mod upload;
|
||||
@@ -446,6 +447,111 @@ web_ffi!(web_app_route_rss, |args: &Value| {
|
||||
Ok(app)
|
||||
});
|
||||
|
||||
web_ffi!(web_app_redirect, |args: &Value| {
|
||||
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
||||
let from = normalize_route_path(arg_str(args, "from").or_else(|_| arg_str(args, "path"))?)?;
|
||||
let to = arg_str(args, "to")?.to_string();
|
||||
let permanent = match args
|
||||
.get("permanent")
|
||||
.or_else(|| args.get("永久"))
|
||||
.cloned()
|
||||
.unwrap_or(json!(false))
|
||||
{
|
||||
Value::Bool(b) => b,
|
||||
Value::String(s) => matches!(s.as_str(), "true" | "True" | "1" | "yes" | "真"),
|
||||
Value::Number(n) => n.as_i64().unwrap_or(0) != 0,
|
||||
_ => false,
|
||||
};
|
||||
let obj = app
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| "app must be a map".to_string())?;
|
||||
let mut redirects = obj
|
||||
.get("redirects")
|
||||
.and_then(|v| v.as_object())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
redirects.insert(from, json!({ "to": to, "permanent": permanent }));
|
||||
obj.insert("redirects".into(), Value::Object(redirects));
|
||||
Ok(app)
|
||||
});
|
||||
|
||||
web_ffi!(web_app_error_page, |args: &Value| {
|
||||
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
||||
let status = args
|
||||
.get("status")
|
||||
.or_else(|| args.get("状态"))
|
||||
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
||||
.unwrap_or(404) as u16;
|
||||
let page = args
|
||||
.get("page")
|
||||
.or_else(|| args.get("页面"))
|
||||
.cloned()
|
||||
.ok_or_else(|| "missing `page`".to_string())?;
|
||||
let obj = app
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| "app must be a map".to_string())?;
|
||||
let key = match status {
|
||||
500 => "page_500",
|
||||
_ => "page_404",
|
||||
};
|
||||
obj.insert(key.into(), page);
|
||||
Ok(app)
|
||||
});
|
||||
|
||||
web_ffi!(web_app_sitemap, |args: &Value| {
|
||||
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
||||
let path = normalize_route_path(arg_str(args, "path").unwrap_or("/sitemap.xml"))?;
|
||||
let base = arg_str_opt(args, "base").unwrap_or("").to_string();
|
||||
let table = arg_str_opt(args, "table").map(|s| s.to_string());
|
||||
let loc = arg_str_opt(args, "loc").unwrap_or("path").to_string();
|
||||
let limit = args
|
||||
.get("limit")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(1000);
|
||||
let items = args.get("items").cloned().unwrap_or(json!([]));
|
||||
let obj = app
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| "app must be a map".to_string())?;
|
||||
let mut routes = obj
|
||||
.get("sitemap_routes")
|
||||
.and_then(|v| v.as_object())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
routes.insert(
|
||||
path,
|
||||
json!({
|
||||
"base": base,
|
||||
"table": table,
|
||||
"loc": loc,
|
||||
"limit": limit,
|
||||
"items": items,
|
||||
}),
|
||||
);
|
||||
obj.insert("sitemap_routes".into(), Value::Object(routes));
|
||||
Ok(app)
|
||||
});
|
||||
|
||||
web_ffi!(web_app_robots, |args: &Value| {
|
||||
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
||||
let body = arg_str_opt(args, "body").map(|s| s.to_string());
|
||||
let sitemap_url = arg_str_opt(args, "sitemap").map(|s| s.to_string());
|
||||
let text = match body.filter(|s| !s.is_empty()) {
|
||||
Some(b) => b,
|
||||
None => crate::sitemap::build_robots(sitemap_url.as_deref()),
|
||||
};
|
||||
let obj = app
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| "app must be a map".to_string())?;
|
||||
obj.insert("robots_body".into(), json!(text));
|
||||
Ok(app)
|
||||
});
|
||||
|
||||
web_ffi!(web_sitemap_build, |args: &Value| {
|
||||
let base = arg_str_opt(args, "base").unwrap_or("");
|
||||
let items = args.get("items").cloned().unwrap_or(json!([]));
|
||||
Ok(crate::sitemap::sitemap_json(base, &items))
|
||||
});
|
||||
|
||||
fn storage_url_arg(args: &Value, key: &str) -> Result<String, String> {
|
||||
if let Some(s) = arg_str_opt(args, key) {
|
||||
return Ok(s.to_string());
|
||||
@@ -1096,6 +1202,16 @@ web_ffi!(web_app_middleware, |args: &Value| {
|
||||
};
|
||||
m.insert("access_log".into(), json!(on));
|
||||
}
|
||||
if let Some(cc) = args
|
||||
.get("cache_control")
|
||||
.or_else(|| args.get("缓存控制"))
|
||||
.and_then(|v| v.as_str())
|
||||
{
|
||||
let s = cc.trim();
|
||||
if !s.is_empty() {
|
||||
m.insert("cache_control".into(), json!(s));
|
||||
}
|
||||
}
|
||||
if let Some(bl) = args.get("body_limit") {
|
||||
let n = bl
|
||||
.as_u64()
|
||||
@@ -1221,6 +1337,11 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
rss_routes,
|
||||
upload_routes,
|
||||
download_routes,
|
||||
redirects,
|
||||
sitemap_routes,
|
||||
robots_body,
|
||||
page_404,
|
||||
page_500,
|
||||
middleware,
|
||||
cookie_secure,
|
||||
) = if args.get("page").is_some() || args.get("host").is_some() {
|
||||
@@ -1268,6 +1389,11 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
HashMap::new(),
|
||||
HashMap::new(),
|
||||
HashMap::new(),
|
||||
HashMap::new(),
|
||||
HashMap::new(),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
middleware::Middleware::default(),
|
||||
cookie_secure,
|
||||
)
|
||||
@@ -1375,6 +1501,38 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut redirects = HashMap::new();
|
||||
if let Some(obj) = app.get("redirects").and_then(|v| v.as_object()) {
|
||||
for (k, v) in obj {
|
||||
let to = v
|
||||
.get("to")
|
||||
.and_then(|x| x.as_str())
|
||||
.unwrap_or("/")
|
||||
.to_string();
|
||||
let permanent = v
|
||||
.get("permanent")
|
||||
.and_then(|x| x.as_bool())
|
||||
.unwrap_or(false);
|
||||
redirects.insert(k.clone(), (to, permanent));
|
||||
}
|
||||
}
|
||||
let mut sitemap_routes = HashMap::new();
|
||||
if let Some(obj) = app.get("sitemap_routes").and_then(|v| v.as_object()) {
|
||||
for (k, v) in obj {
|
||||
sitemap_routes.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
let robots_body = app
|
||||
.get("robots_body")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
let page_404 = app.get("page_404").cloned().filter(|v| !v.is_null());
|
||||
let page_500 = app.get("page_500").cloned().filter(|v| !v.is_null());
|
||||
if app.get("tls_cert").is_some() || app.get("tls_key").is_some() {
|
||||
eprintln!(
|
||||
"marqdo web: in-process TLS is not enabled; terminate HTTPS at a reverse proxy (nginx/caddy) and set cookie_secure=True"
|
||||
);
|
||||
}
|
||||
let static_dir = app
|
||||
.get("static_dir")
|
||||
.and_then(|v| v.as_str())
|
||||
@@ -1432,6 +1590,11 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
rss_routes,
|
||||
upload_routes,
|
||||
download_routes,
|
||||
redirects,
|
||||
sitemap_routes,
|
||||
robots_body,
|
||||
page_404,
|
||||
page_500,
|
||||
middleware,
|
||||
cookie_secure,
|
||||
)
|
||||
@@ -1460,6 +1623,11 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
rss_routes,
|
||||
upload_routes,
|
||||
download_routes,
|
||||
redirects,
|
||||
sitemap_routes,
|
||||
robots_body,
|
||||
page_404,
|
||||
page_500,
|
||||
&middleware,
|
||||
)
|
||||
});
|
||||
@@ -1549,6 +1717,23 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
|
||||
"app,path,table,limit,order,title,link,description",
|
||||
web_app_route_rss as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_app_redirect",
|
||||
"app,from,to,permanent",
|
||||
web_app_redirect as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_app_error_page",
|
||||
"app,status,page",
|
||||
web_app_error_page as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_app_sitemap",
|
||||
"app,path,base,table,loc,limit,items",
|
||||
web_app_sitemap as PluginFn,
|
||||
),
|
||||
("web_app_robots", "app,body,sitemap", web_app_robots as PluginFn),
|
||||
("web_sitemap_build", "base,items", web_sitemap_build as PluginFn),
|
||||
(
|
||||
"web_app_upload",
|
||||
"app,path,field,storage,prefix,max_bytes,types",
|
||||
@@ -1651,7 +1836,7 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
|
||||
),
|
||||
(
|
||||
"web_app_middleware",
|
||||
"app,cors,security,compress,body_limit,json_routes,access_log",
|
||||
"app,cors,security,compress,body_limit,json_routes,access_log,cache_control",
|
||||
web_app_middleware as PluginFn,
|
||||
),
|
||||
("web_form_new", "table,action,id", web_form_new as PluginFn),
|
||||
|
||||
@@ -43,6 +43,8 @@ pub struct Middleware {
|
||||
pub body_limit: Option<u64>,
|
||||
/// Log `METHOD path status duration_ms` to stderr for each request.
|
||||
pub access_log: bool,
|
||||
/// Global `Cache-Control` response header (e.g. `public, max-age=3600`).
|
||||
pub cache_control: Option<String>,
|
||||
/// JSON API routes: `path -> { method, table, where?, order?, limit? }`.
|
||||
pub json_routes: Vec<(String, JsonRoute)>,
|
||||
}
|
||||
@@ -89,6 +91,11 @@ pub fn parse(app: &Value) -> Middleware {
|
||||
.get("access_log")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
mw.cache_control = obj
|
||||
.get("cache_control")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty());
|
||||
mw.body_limit = obj
|
||||
.get("body_limit")
|
||||
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
||||
@@ -226,6 +233,15 @@ pub fn apply(
|
||||
app = app.layer(CompressionLayer::new());
|
||||
}
|
||||
|
||||
if let Some(ref cc) = mw.cache_control {
|
||||
if let Ok(v) = HeaderValue::from_str(cc) {
|
||||
app = app.layer(SetResponseHeaderLayer::overriding(
|
||||
header::CACHE_CONTROL,
|
||||
v,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Request body limit
|
||||
if let Some(bytes) = mw.body_limit {
|
||||
app = app.layer(RequestBodyLimitLayer::new(bytes as usize));
|
||||
@@ -457,6 +473,9 @@ pub fn summary(app: &Value) -> String {
|
||||
if mw.access_log {
|
||||
parts.push("access_log".to_string());
|
||||
}
|
||||
if mw.cache_control.is_some() {
|
||||
parts.push("cache_control".to_string());
|
||||
}
|
||||
if !mw.json_routes.is_empty() {
|
||||
parts.push(format!("json:{}", mw.json_routes.len()));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
//! sitemap.xml / robots.txt helpers (W7).
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
fn cell_str(v: &Value) -> String {
|
||||
match v {
|
||||
Value::Null => String::new(),
|
||||
Value::String(s) => s.clone(),
|
||||
Value::Bool(b) => b.to_string(),
|
||||
Value::Number(n) => n.to_string(),
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn xml_escape(s: &str) -> String {
|
||||
s.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
.replace('"', """)
|
||||
.replace('\'', "'")
|
||||
}
|
||||
|
||||
/// Build a sitemap.xml document from rows.
|
||||
///
|
||||
/// Each row may use keys: `loc`/`url`/`路径`, optional `lastmod`/`更新`,
|
||||
/// `changefreq`/`频率`, `priority`/`优先级`.
|
||||
pub fn build_sitemap(base: &str, items: &Value) -> String {
|
||||
let base = base.trim_end_matches('/');
|
||||
let rows: Vec<Value> = match items {
|
||||
Value::Array(a) => a
|
||||
.iter()
|
||||
.map(|row| match row {
|
||||
Value::String(s) => json!({ "loc": s }),
|
||||
Value::Object(_) => row.clone(),
|
||||
other => json!({ "loc": cell_str(other) }),
|
||||
})
|
||||
.collect(),
|
||||
Value::Object(m) => {
|
||||
// Columnar GFM: { loc: [...], ... }
|
||||
let locs = m
|
||||
.get("loc")
|
||||
.or_else(|| m.get("路径"))
|
||||
.or_else(|| m.get("path"))
|
||||
.or_else(|| m.get("url"));
|
||||
match locs {
|
||||
Some(Value::Array(a)) => a
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, loc)| {
|
||||
let mut obj = serde_json::Map::new();
|
||||
obj.insert("loc".into(), loc.clone());
|
||||
for (k, v) in m {
|
||||
if k == "loc" || k == "路径" || k == "path" || k == "url" {
|
||||
continue;
|
||||
}
|
||||
if let Some(Value::Array(col)) = Some(v) {
|
||||
if let Some(cell) = col.get(i) {
|
||||
obj.insert(k.clone(), cell.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Object(obj)
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let mut out = String::from(
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
|
||||
<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n",
|
||||
);
|
||||
for row in &rows {
|
||||
let Some(obj) = row.as_object() else {
|
||||
continue;
|
||||
};
|
||||
let loc_raw = obj
|
||||
.get("loc")
|
||||
.or_else(|| obj.get("url"))
|
||||
.or_else(|| obj.get("路径"))
|
||||
.or_else(|| obj.get("path"))
|
||||
.map(cell_str)
|
||||
.unwrap_or_default();
|
||||
if loc_raw.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let loc = if loc_raw.starts_with("http://") || loc_raw.starts_with("https://") {
|
||||
loc_raw
|
||||
} else if loc_raw.starts_with('/') {
|
||||
format!("{base}{loc_raw}")
|
||||
} else {
|
||||
format!("{base}/{loc_raw}")
|
||||
};
|
||||
out.push_str(" <url>\n");
|
||||
out.push_str(&format!(" <loc>{}</loc>\n", xml_escape(&loc)));
|
||||
if let Some(lm) = obj
|
||||
.get("lastmod")
|
||||
.or_else(|| obj.get("更新"))
|
||||
.map(cell_str)
|
||||
.filter(|s| !s.is_empty())
|
||||
{
|
||||
out.push_str(&format!(" <lastmod>{}</lastmod>\n", xml_escape(&lm)));
|
||||
}
|
||||
if let Some(cf) = obj
|
||||
.get("changefreq")
|
||||
.or_else(|| obj.get("频率"))
|
||||
.map(cell_str)
|
||||
.filter(|s| !s.is_empty())
|
||||
{
|
||||
out.push_str(&format!(
|
||||
" <changefreq>{}</changefreq>\n",
|
||||
xml_escape(&cf)
|
||||
));
|
||||
}
|
||||
if let Some(pr) = obj
|
||||
.get("priority")
|
||||
.or_else(|| obj.get("优先级"))
|
||||
.map(cell_str)
|
||||
.filter(|s| !s.is_empty())
|
||||
{
|
||||
out.push_str(&format!(" <priority>{}</priority>\n", xml_escape(&pr)));
|
||||
}
|
||||
out.push_str(" </url>\n");
|
||||
}
|
||||
out.push_str("</urlset>\n");
|
||||
out
|
||||
}
|
||||
|
||||
/// Default robots.txt body allowing all and pointing at a sitemap URL.
|
||||
pub fn build_robots(sitemap_url: Option<&str>) -> String {
|
||||
let mut out = String::from("User-agent: *\nAllow: /\n");
|
||||
if let Some(u) = sitemap_url.filter(|s| !s.is_empty()) {
|
||||
out.push_str(&format!("Sitemap: {u}\n"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// ABI helper returning `{ body }`.
|
||||
#[allow(dead_code)]
|
||||
pub fn robots_json(sitemap_url: Option<&str>, body: Option<&str>) -> Value {
|
||||
let text = match body.filter(|s| !s.is_empty()) {
|
||||
Some(b) => b.to_string(),
|
||||
None => build_robots(sitemap_url),
|
||||
};
|
||||
json!({ "body": text })
|
||||
}
|
||||
@@ -66,7 +66,10 @@ fn boolish(v: &Value) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Schema table → `[{name,type,nullable}, …]`
|
||||
const UNIQUE_KEYS: &[&str] = &["唯一", "unique", "uniq"];
|
||||
const INDEX_KEYS: &[&str] = &["索引", "index", "idx"];
|
||||
|
||||
/// Schema table → `[{name,type,nullable,unique,index}, …]`
|
||||
pub fn as_fields(table: &Value) -> Value {
|
||||
match table {
|
||||
Value::Array(rows) => {
|
||||
@@ -81,7 +84,15 @@ pub fn as_fields(table: &Value) -> Value {
|
||||
.map(cell_str)
|
||||
.unwrap_or_else(|| "text".into());
|
||||
let nullable = pick(m, NULL_KEYS).map(boolish).unwrap_or(true);
|
||||
out.push(json!({ "name": name, "type": ty, "nullable": nullable }));
|
||||
let unique = pick(m, UNIQUE_KEYS).map(boolish).unwrap_or(false);
|
||||
let index = pick(m, INDEX_KEYS).map(boolish).unwrap_or(false);
|
||||
out.push(json!({
|
||||
"name": name,
|
||||
"type": ty,
|
||||
"nullable": nullable,
|
||||
"unique": unique,
|
||||
"index": index,
|
||||
}));
|
||||
}
|
||||
}
|
||||
Value::Array(out)
|
||||
@@ -90,6 +101,8 @@ pub fn as_fields(table: &Value) -> Value {
|
||||
let names = pick(m, FIELD_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let types = pick(m, TYPE_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let nulls = pick(m, NULL_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let uniques = pick(m, UNIQUE_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let indexes = pick(m, INDEX_KEYS).map(as_str_list).unwrap_or_default();
|
||||
let mut out = Vec::new();
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
if name.is_empty() {
|
||||
@@ -100,7 +113,21 @@ pub fn as_fields(table: &Value) -> Value {
|
||||
.get(i)
|
||||
.map(|s| boolish(&Value::String(s.clone())))
|
||||
.unwrap_or(true);
|
||||
out.push(json!({ "name": name, "type": ty, "nullable": nullable }));
|
||||
let unique = uniques
|
||||
.get(i)
|
||||
.map(|s| boolish(&Value::String(s.clone())))
|
||||
.unwrap_or(false);
|
||||
let index = indexes
|
||||
.get(i)
|
||||
.map(|s| boolish(&Value::String(s.clone())))
|
||||
.unwrap_or(false);
|
||||
out.push(json!({
|
||||
"name": name,
|
||||
"type": ty,
|
||||
"nullable": nullable,
|
||||
"unique": unique,
|
||||
"index": index,
|
||||
}));
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user