ext/web W4c: SEO meta, Markdown render, RSS, pagination UI
Add lib/net markdown_parse, page.meta/paginate and app.route_rss author APIs, GFM Markdown article bodies, head SEO tags, list pagination nav, and RSS 2.0 feed routes — keeping tables + class methods as the author surface. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
be6223f1fb
commit
e7c9c21a49
18 files changed
+671
-60
No files matched your search
@@ -19,6 +19,7 @@ use crate::form;
|
||||
use crate::middleware::Middleware;
|
||||
use crate::rate_limit;
|
||||
use crate::render;
|
||||
use crate::rss;
|
||||
use crate::session;
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -71,6 +72,7 @@ pub fn listen(
|
||||
session_ttl: u64,
|
||||
cookie_secure: bool,
|
||||
ws_routes: HashMap<String, bool>,
|
||||
rss_routes: HashMap<String, Value>,
|
||||
middleware: &Middleware,
|
||||
) -> Result<Value, String> {
|
||||
let mut form_owners = HashMap::new();
|
||||
@@ -179,6 +181,21 @@ pub fn listen(
|
||||
);
|
||||
}
|
||||
|
||||
let mut rss_paths: Vec<String> = rss_routes.keys().cloned().collect();
|
||||
rss_paths.sort();
|
||||
for path in rss_paths {
|
||||
let cfg = rss_routes.get(&path).cloned().unwrap_or_default();
|
||||
let route_path = path.clone();
|
||||
app = app.route(
|
||||
&path,
|
||||
get(move |State(st): State<Arc<AppState>>| {
|
||||
let cfg = cfg.clone();
|
||||
let route_path = route_path.clone();
|
||||
async move { rss_feed(&st, &route_path, &cfg) }
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
let mount = normalize_static_mount(static_mount);
|
||||
if let Some(dir) = static_dir {
|
||||
if !dir.is_dir() {
|
||||
@@ -232,6 +249,40 @@ pub fn normalize_static_mount(raw: &str) -> String {
|
||||
m
|
||||
}
|
||||
|
||||
fn rss_feed(st: &AppState, _path: &str, cfg: &Value) -> Response {
|
||||
let Some(url) = st.db_url.as_deref() else {
|
||||
return Html(String::from("<p>no database</p>")).into_response();
|
||||
};
|
||||
let table = cfg
|
||||
.get("table")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("posts");
|
||||
let limit = cfg
|
||||
.get("limit")
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(20);
|
||||
let order = cfg.get("order").and_then(|v| v.as_str());
|
||||
let title = cfg
|
||||
.get("title")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("Feed");
|
||||
let link = cfg.get("link").and_then(|v| v.as_str()).unwrap_or("/");
|
||||
let description = cfg
|
||||
.get("description")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let rows = db::select_order(url, table, limit, None, order, None, None)
|
||||
.ok()
|
||||
.and_then(|v| v.get("rows").and_then(|r| r.as_array()).cloned())
|
||||
.unwrap_or_default();
|
||||
let xml = rss::build_rss(title, link, description, &rows);
|
||||
(
|
||||
[(axum::http::header::CONTENT_TYPE, "application/rss+xml; charset=utf-8")],
|
||||
xml,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
async fn home(State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap) -> Response {
|
||||
let (_, csrf, set_cookie) = resolve_session(&headers);
|
||||
let html = render::render_page(&st.page, st.db_url.as_deref(), Some(&csrf));
|
||||
|
||||
@@ -4,10 +4,12 @@ mod compose;
|
||||
mod db;
|
||||
mod form;
|
||||
mod http;
|
||||
mod markdown;
|
||||
mod middleware;
|
||||
mod password;
|
||||
mod rate_limit;
|
||||
mod render;
|
||||
mod rss;
|
||||
mod session;
|
||||
mod table;
|
||||
mod ws;
|
||||
@@ -345,6 +347,92 @@ web_ffi!(web_page_detail, |args: &Value| {
|
||||
Ok(Value::Object(obj))
|
||||
});
|
||||
|
||||
web_ffi!(web_page_meta, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let meta = args
|
||||
.get("meta")
|
||||
.or_else(|| args.get("table"))
|
||||
.cloned()
|
||||
.unwrap_or(json!({}));
|
||||
let mut obj = page.as_object().cloned().unwrap_or_default();
|
||||
obj.insert("meta".into(), Value::Object(crate::table::as_meta_map(&meta)));
|
||||
Ok(Value::Object(obj))
|
||||
});
|
||||
|
||||
web_ffi!(web_page_paginate, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let offset = args
|
||||
.get("offset")
|
||||
.and_then(|v| v.as_i64().or_else(|| v.as_u64().map(|u| u as i64)))
|
||||
.unwrap_or(0);
|
||||
let limit = args
|
||||
.get("limit")
|
||||
.and_then(|v| v.as_i64().or_else(|| v.as_u64().map(|u| u as i64)))
|
||||
.unwrap_or(10);
|
||||
let path = arg_str_opt(args, "path").unwrap_or("/").to_string();
|
||||
let mut obj = page.as_object().cloned().unwrap_or_default();
|
||||
obj.insert(
|
||||
"paginate".into(),
|
||||
json!({ "offset": offset, "limit": limit, "path": path }),
|
||||
);
|
||||
Ok(Value::Object(obj))
|
||||
});
|
||||
|
||||
web_ffi!(web_rss_build, |args: &Value| {
|
||||
let title = arg_str_opt(args, "title").unwrap_or("Feed");
|
||||
let link = arg_str_opt(args, "link").unwrap_or("/");
|
||||
let description = arg_str_opt(args, "description").unwrap_or("");
|
||||
let items = args
|
||||
.get("items")
|
||||
.or_else(|| args.get("rows"))
|
||||
.and_then(|v| v.as_array())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
Ok(Value::String(rss::build_rss(
|
||||
title,
|
||||
link,
|
||||
description,
|
||||
&items,
|
||||
)))
|
||||
});
|
||||
|
||||
web_ffi!(web_app_route_rss, |args: &Value| {
|
||||
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
||||
let path = normalize_route_path(arg_str(args, "path")?)?;
|
||||
let table = arg_str(args, "table")?.to_string();
|
||||
let limit = args
|
||||
.get("limit")
|
||||
.and_then(|v| v.as_i64().or_else(|| v.as_u64().map(|u| u as i64)))
|
||||
.unwrap_or(20);
|
||||
let order = arg_str_opt(args, "order").unwrap_or("-created_at").to_string();
|
||||
let title = arg_str_opt(args, "title").unwrap_or("Feed").to_string();
|
||||
let link = arg_str_opt(args, "link").unwrap_or("/").to_string();
|
||||
let description = arg_str_opt(args, "description")
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let obj = app
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| "app must be a map".to_string())?;
|
||||
let mut rss_routes = obj
|
||||
.get("rss_routes")
|
||||
.and_then(|v| v.as_object())
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
rss_routes.insert(
|
||||
path,
|
||||
json!({
|
||||
"table": table,
|
||||
"limit": limit,
|
||||
"order": order,
|
||||
"title": title,
|
||||
"link": link,
|
||||
"description": description,
|
||||
}),
|
||||
);
|
||||
obj.insert("rss_routes".into(), Value::Object(rss_routes));
|
||||
Ok(app)
|
||||
});
|
||||
|
||||
web_ffi!(web_compose_form, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let form = args
|
||||
@@ -878,6 +966,7 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
auth_users,
|
||||
session_ttl,
|
||||
ws_routes,
|
||||
rss_routes,
|
||||
middleware,
|
||||
cookie_secure,
|
||||
) = if args.get("page").is_some() || args.get("host").is_some() {
|
||||
@@ -922,6 +1011,7 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
auth_users,
|
||||
session_ttl,
|
||||
HashMap::new(),
|
||||
HashMap::new(),
|
||||
middleware::Middleware::default(),
|
||||
cookie_secure,
|
||||
)
|
||||
@@ -971,6 +1061,12 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
ws_routes.insert(k.clone(), echo);
|
||||
}
|
||||
}
|
||||
let mut rss_routes = HashMap::new();
|
||||
if let Some(obj) = app.get("rss_routes").and_then(|v| v.as_object()) {
|
||||
for (k, v) in obj {
|
||||
rss_routes.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
let static_dir = app
|
||||
.get("static_dir")
|
||||
.and_then(|v| v.as_str())
|
||||
@@ -1025,6 +1121,7 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
auth_users,
|
||||
session_ttl,
|
||||
ws_routes,
|
||||
rss_routes,
|
||||
middleware,
|
||||
cookie_secure,
|
||||
)
|
||||
@@ -1050,6 +1147,7 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
session_ttl,
|
||||
cookie_secure,
|
||||
ws_routes,
|
||||
rss_routes,
|
||||
&middleware,
|
||||
)
|
||||
});
|
||||
@@ -1119,6 +1217,26 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
|
||||
"page,detail",
|
||||
web_page_detail as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_page_meta",
|
||||
"page,meta",
|
||||
web_page_meta as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_page_paginate",
|
||||
"page,offset,limit,path",
|
||||
web_page_paginate as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_rss_build",
|
||||
"title,link,description,items",
|
||||
web_rss_build as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_app_route_rss",
|
||||
"app,path,table,limit,order,title,link,description",
|
||||
web_app_route_rss as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_style",
|
||||
"name,table",
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Markdown → HTML for article bodies (GFM subset via pulldown-cmark).
|
||||
|
||||
use pulldown_cmark::{html, Options, Parser};
|
||||
|
||||
pub fn to_html(md: &str) -> String {
|
||||
let mut opts = Options::empty();
|
||||
opts.insert(
|
||||
Options::ENABLE_STRIKETHROUGH
|
||||
| Options::ENABLE_TABLES
|
||||
| Options::ENABLE_TASKLISTS,
|
||||
);
|
||||
let parser = Parser::new_ext(md, opts);
|
||||
let mut html_out = String::new();
|
||||
html::push_html(&mut html_out, parser);
|
||||
format!("<div class=\"article-body md\">{html_out}</div>")
|
||||
}
|
||||
+138
-58
@@ -3,6 +3,7 @@
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::db;
|
||||
use crate::markdown;
|
||||
use crate::table::{as_bind, normalize_ref, normalize_slot, parse_site_path, project_rows, SitePath};
|
||||
|
||||
fn esc(s: &str) -> String {
|
||||
@@ -77,7 +78,7 @@ fn resolve_links(raw: Option<&Value>, db_url: Option<&str>) -> Vec<(String, Stri
|
||||
let Some(table) = table else {
|
||||
return Vec::new();
|
||||
};
|
||||
let data = select_page_data(url, &table, raw, 200);
|
||||
let data = select_page_data(url, &table, raw, 200, 0);
|
||||
let rows = data
|
||||
.get("rows")
|
||||
.and_then(|v| v.as_array())
|
||||
@@ -127,27 +128,38 @@ fn render_ul(links: &[(String, String)], class: &str) -> String {
|
||||
s
|
||||
}
|
||||
|
||||
fn resolve_main(args: &Value, db_url: Option<&str>) -> (String, Vec<Map<String, Value>>) {
|
||||
fn resolve_main(args: &Value, db_url: Option<&str>) -> (String, Vec<Map<String, Value>>, Option<i64>) {
|
||||
let intro = args
|
||||
.get("intro")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let Some(main) = args.get("main") else {
|
||||
return (intro, Vec::new());
|
||||
return (intro, Vec::new(), None);
|
||||
};
|
||||
let binds = as_bind(main);
|
||||
let arr = binds.as_array().cloned().unwrap_or_default();
|
||||
if arr.is_empty() {
|
||||
return (intro, Vec::new());
|
||||
return (intro, Vec::new(), None);
|
||||
}
|
||||
let Some(url) = db_url else {
|
||||
return (intro, Vec::new());
|
||||
return (intro, Vec::new(), None);
|
||||
};
|
||||
let Some(table) = crate::table::bind_table_name(&arr) else {
|
||||
return (intro, Vec::new());
|
||||
return (intro, Vec::new(), None);
|
||||
};
|
||||
let data = select_page_data(url, &table, args, 200);
|
||||
let limit = args
|
||||
.get("paginate")
|
||||
.and_then(|p| p.get("limit"))
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(200);
|
||||
let offset = args
|
||||
.get("paginate")
|
||||
.and_then(|p| p.get("offset"))
|
||||
.and_then(|v| v.as_i64())
|
||||
.unwrap_or(0);
|
||||
let data = select_page_data(url, &table, args, limit, offset);
|
||||
let total = data.get("total").and_then(|v| v.as_i64());
|
||||
let rows = data
|
||||
.get("rows")
|
||||
.and_then(|v| v.as_array())
|
||||
@@ -161,7 +173,7 @@ fn resolve_main(args: &Value, db_url: Option<&str>) -> (String, Vec<Map<String,
|
||||
.into_iter()
|
||||
.filter_map(|v| v.as_object().cloned())
|
||||
.collect();
|
||||
(intro, items)
|
||||
(intro, items, total)
|
||||
}
|
||||
|
||||
/// Run the page's DB query: `where` (with `{param}` placeholders resolved from
|
||||
@@ -171,6 +183,7 @@ fn select_page_data(
|
||||
table: &str,
|
||||
args: &Value,
|
||||
limit: i64,
|
||||
offset: i64,
|
||||
) -> Value {
|
||||
let mut where_v = args.get("query").cloned();
|
||||
if let Some(m) = where_v.as_ref().and_then(|v| v.as_object()) {
|
||||
@@ -187,11 +200,20 @@ fn select_page_data(
|
||||
}
|
||||
}
|
||||
let order = args.get("order").and_then(|v| v.as_str());
|
||||
if order.is_some_and(|s| !s.trim().is_empty()) {
|
||||
db::select_order(url, table, limit, where_v.as_ref(), order, None, None)
|
||||
} else {
|
||||
db::select(url, table, limit, where_v.as_ref())
|
||||
}
|
||||
let paginate = args.get("paginate").is_some();
|
||||
db::select_order(
|
||||
url,
|
||||
table,
|
||||
limit,
|
||||
where_v.as_ref(),
|
||||
order.filter(|s| !s.trim().is_empty()),
|
||||
if paginate || offset > 0 {
|
||||
Some(offset)
|
||||
} else {
|
||||
None
|
||||
},
|
||||
None,
|
||||
)
|
||||
.unwrap_or(json!({ "rows": [] }))
|
||||
}
|
||||
|
||||
@@ -318,9 +340,103 @@ a:hover { color:var(--accent); }
|
||||
.article-body { line-height:1.75; color:var(--ink); }
|
||||
.article-p { margin:0 0 1rem; white-space:pre-line; }
|
||||
.article-h2 { margin:1.5rem 0 .75rem; }
|
||||
.article-code { background:#f5f5f4; border:1px solid var(--line); border-radius:6px; padding:1rem; overflow-x:auto; font-size:.9rem; }
|
||||
.article-body.md { line-height: 1.75; }
|
||||
.article-body.md pre { background:#f5f5f4; border:1px solid var(--line); border-radius:6px; padding:1rem; overflow-x:auto; }
|
||||
.article-body.md code { font-size:.9em; }
|
||||
.pagination { display:flex; gap:1rem; align-items:center; margin:1.5rem 0; font-size:.95rem; }
|
||||
.pagination a { color:var(--accent); text-decoration:none; }
|
||||
.pagination a:hover { text-decoration:underline; }
|
||||
.pagination .page-status { color:var(--muted); }
|
||||
"#;
|
||||
|
||||
fn head_html(args: &Value, default_title: &str) -> String {
|
||||
let meta = args.get("meta").and_then(|v| v.as_object());
|
||||
let page_title = meta
|
||||
.and_then(|m| m.get("title"))
|
||||
.map(text)
|
||||
.filter(|s| !s.is_empty())
|
||||
.unwrap_or_else(|| default_title.to_string());
|
||||
let mut s = format!("<title>{}</title>", esc(&page_title));
|
||||
if let Some(m) = meta {
|
||||
for (k, v) in m {
|
||||
if k == "title" {
|
||||
continue;
|
||||
}
|
||||
let val = text(v);
|
||||
if val.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match k.as_str() {
|
||||
"description" => {
|
||||
s.push_str(&format!(
|
||||
"<meta name=\"description\" content=\"{}\"/>",
|
||||
esc(&val)
|
||||
));
|
||||
}
|
||||
"canonical" => {
|
||||
s.push_str(&format!("<link rel=\"canonical\" href=\"{}\"/>", esc(&val)));
|
||||
}
|
||||
k if k.starts_with("og:") => {
|
||||
s.push_str(&format!(
|
||||
"<meta property=\"{}\" content=\"{}\"/>",
|
||||
esc(k),
|
||||
esc(&val)
|
||||
));
|
||||
}
|
||||
other => {
|
||||
s.push_str(&format!(
|
||||
"<meta name=\"{}\" content=\"{}\"/>",
|
||||
esc(other),
|
||||
esc(&val)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
fn render_pagination(args: &Value, total: i64, item_count: usize) -> String {
|
||||
let Some(p) = args.get("paginate") else {
|
||||
return String::new();
|
||||
};
|
||||
let offset = p.get("offset").and_then(|v| v.as_i64()).unwrap_or(0);
|
||||
let limit = p.get("limit").and_then(|v| v.as_i64()).unwrap_or(10);
|
||||
if limit <= 0 {
|
||||
return String::new();
|
||||
}
|
||||
let path = p
|
||||
.get("path")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("/")
|
||||
.to_string();
|
||||
let mut s = String::from("<nav class=\"pagination\" aria-label=\"Pagination\">");
|
||||
if offset > 0 {
|
||||
let prev = offset.saturating_sub(limit);
|
||||
s.push_str(&format!(
|
||||
"<a class=\"page-prev\" href=\"{}?offset={}\">← Previous</a> ",
|
||||
esc(&path),
|
||||
prev
|
||||
));
|
||||
}
|
||||
let end = offset + item_count as i64;
|
||||
s.push_str(&format!(
|
||||
"<span class=\"page-status\">{}–{} of {}</span> ",
|
||||
offset + 1,
|
||||
end.min(total),
|
||||
total
|
||||
));
|
||||
if end < total {
|
||||
s.push_str(&format!(
|
||||
"<a class=\"page-next\" href=\"{}?offset={}\">Next →</a>",
|
||||
esc(&path),
|
||||
end
|
||||
));
|
||||
}
|
||||
s.push_str("</nav>");
|
||||
s
|
||||
}
|
||||
|
||||
pub fn render_page(args: &Value, db_url: Option<&str>, csrf: Option<&str>) -> String {
|
||||
render_page_ex(args, db_url, None, None, csrf)
|
||||
}
|
||||
@@ -350,7 +466,7 @@ pub fn render_page_ex(
|
||||
let nav = resolve_links(args.get("nav"), db_url);
|
||||
let side = resolve_links(args.get("sidebar"), db_url);
|
||||
let foot = resolve_links(args.get("footer"), db_url);
|
||||
let (intro, items) = resolve_main(args, db_url);
|
||||
let (intro, items, total) = resolve_main(args, db_url);
|
||||
|
||||
let has_side = args.get("sidebar").is_some() || !side.is_empty();
|
||||
let body_class = if has_side {
|
||||
@@ -390,6 +506,9 @@ pub fn render_page_ex(
|
||||
}
|
||||
main_html.push_str("</section>");
|
||||
}
|
||||
if let Some(t) = total {
|
||||
main_html.push_str(&render_pagination(args, t, items.len()));
|
||||
}
|
||||
}
|
||||
|
||||
format!(
|
||||
@@ -397,7 +516,7 @@ pub fn render_page_ex(
|
||||
<html lang="zh-CN"><head>
|
||||
<meta charset="utf-8"/>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"/>
|
||||
<title>{title}</title>
|
||||
{head}
|
||||
<style>{SHELL_CSS}{extra}</style>
|
||||
</head>
|
||||
<body class="{body_class}">
|
||||
@@ -406,7 +525,7 @@ pub fn render_page_ex(
|
||||
<main class="{main_class}"{main_attrs}>{main_html}</main>
|
||||
<footer class="{foot_class}"{foot_attrs}>{foot_ul}</footer>
|
||||
</body></html>"#,
|
||||
title = esc(title),
|
||||
head = head_html(args, title),
|
||||
nav_class = slot_class(args, "nav", "topnav"),
|
||||
nav_attrs = slot_attrs("nav", &parts, args),
|
||||
nav_ul = render_ul(&nav, "nav"),
|
||||
@@ -458,7 +577,7 @@ pub fn render_fragment(args: &Value, db_url: Option<&str>) -> String {
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
let (intro, items) = resolve_main(args, db_url);
|
||||
let (intro, items, _total) = resolve_main(args, db_url);
|
||||
let mut body = String::new();
|
||||
if !intro.is_empty() {
|
||||
body.push_str(&format!("<div class=\"main-intro\">{intro}</div>"));
|
||||
@@ -554,47 +673,8 @@ fn render_article(it: &Map<String, Value>) -> String {
|
||||
));
|
||||
}
|
||||
if !body.is_empty() {
|
||||
s.push_str(&render_article_body(&body));
|
||||
s.push_str(&markdown::to_html(&body));
|
||||
}
|
||||
s.push_str("</article>");
|
||||
s
|
||||
}
|
||||
|
||||
/// Split a Markdown-ish article body into block elements.
|
||||
fn render_article_body(body: &str) -> String {
|
||||
let mut s = String::from("<div class=\"article-body\">");
|
||||
for para in body.split("\n\n") {
|
||||
let para = para.trim();
|
||||
if para.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if let Some(code) = para.strip_prefix("```") {
|
||||
let code = code.strip_suffix("```").unwrap_or(code);
|
||||
s.push_str(&format!(
|
||||
"<pre class=\"article-code\">{}</pre>",
|
||||
esc(code)
|
||||
));
|
||||
continue;
|
||||
}
|
||||
if let Some(h) = para.strip_prefix("## ") {
|
||||
s.push_str(&format!(
|
||||
"<h2 class=\"article-h2\">{}</h2>",
|
||||
esc(h.trim())
|
||||
));
|
||||
continue;
|
||||
}
|
||||
if let Some(h) = para.strip_prefix("# ") {
|
||||
s.push_str(&format!(
|
||||
"<h2 class=\"article-h2\">{}</h2>",
|
||||
esc(h.trim())
|
||||
));
|
||||
continue;
|
||||
}
|
||||
s.push_str(&format!(
|
||||
"<p class=\"article-p\">{}</p>",
|
||||
esc(para).replace('\n', "<br/>")
|
||||
));
|
||||
}
|
||||
s.push_str("</div>");
|
||||
s
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//! RSS 2.0 feed assembly (content-site W4).
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
fn esc(s: &str) -> String {
|
||||
s.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
.replace('"', """)
|
||||
}
|
||||
|
||||
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 pick<'a>(m: &'a serde_json::Map<String, Value>, keys: &[&str]) -> Option<&'a Value> {
|
||||
keys.iter().find_map(|k| m.get(*k))
|
||||
}
|
||||
|
||||
/// Build RSS 2.0 XML from channel metadata and row maps.
|
||||
pub fn build_rss(
|
||||
title: &str,
|
||||
link: &str,
|
||||
description: &str,
|
||||
items: &[Value],
|
||||
) -> String {
|
||||
let mut body = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<rss version="2.0"><channel>
|
||||
<title>{t}</title>
|
||||
<link>{l}</link>
|
||||
<description>{d}</description>
|
||||
"#,
|
||||
t = esc(title),
|
||||
l = esc(link),
|
||||
d = esc(description),
|
||||
);
|
||||
for row in items {
|
||||
let Some(m) = row.as_object() else {
|
||||
continue;
|
||||
};
|
||||
let item_title = pick(m, &["title", "标题"])
|
||||
.map(cell_str)
|
||||
.unwrap_or_default();
|
||||
let item_link = pick(m, &["link", "href", "链接", "slug"])
|
||||
.map(cell_str)
|
||||
.unwrap_or_default();
|
||||
let item_desc = pick(m, &["description", "summary", "摘要", "body", "正文"])
|
||||
.map(cell_str)
|
||||
.unwrap_or_default();
|
||||
let pub_date = pick(m, &["pubDate", "published", "created_at", "发布"])
|
||||
.map(cell_str)
|
||||
.unwrap_or_default();
|
||||
let full_link = if item_link.starts_with("http") {
|
||||
item_link.clone()
|
||||
} else if item_link.starts_with('/') {
|
||||
format!("{link}{item_link}")
|
||||
} else if !item_link.is_empty() {
|
||||
format!("{link}/{item_link}")
|
||||
} else {
|
||||
link.to_string()
|
||||
};
|
||||
body.push_str("<item>");
|
||||
body.push_str(&format!("<title>{}</title>", esc(&item_title)));
|
||||
body.push_str(&format!("<link>{}</link>", esc(&full_link)));
|
||||
body.push_str(&format!(
|
||||
"<description>{}</description>",
|
||||
esc(&item_desc)
|
||||
));
|
||||
if !pub_date.is_empty() {
|
||||
body.push_str(&format!("<pubDate>{}</pubDate>", esc(&pub_date)));
|
||||
}
|
||||
body.push_str("</item>");
|
||||
}
|
||||
body.push_str("</channel></rss>");
|
||||
body
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn rss_contains_item() {
|
||||
let xml = build_rss(
|
||||
"Blog",
|
||||
"http://example.com",
|
||||
"Feed",
|
||||
&[json!({"title": "Hi", "slug": "/post/a", "summary": "text"})],
|
||||
);
|
||||
assert!(xml.contains("<rss"));
|
||||
assert!(xml.contains("<title>Hi</title>"));
|
||||
}
|
||||
}
|
||||
@@ -531,3 +531,50 @@ pub fn project_rows(binds: &[Value], rows: &[Value]) -> Value {
|
||||
}
|
||||
Value::Array(out)
|
||||
}
|
||||
|
||||
const META_KEY_KEYS: &[&str] = &["键", "key", "name"];
|
||||
const META_VAL_KEYS: &[&str] = &["值", "value"];
|
||||
|
||||
/// SEO / OpenGraph meta table → `{title, description, og:…, canonical, …}`.
|
||||
pub fn as_meta_map(table: &Value) -> Map<String, Value> {
|
||||
let mut out = Map::new();
|
||||
match table {
|
||||
Value::Array(rows) => {
|
||||
for row in rows {
|
||||
let Some(obj) = row.as_object() else {
|
||||
continue;
|
||||
};
|
||||
let key = META_KEY_KEYS
|
||||
.iter()
|
||||
.find_map(|k| obj.get(*k))
|
||||
.map(|v| normalize_ref(&meta_text(v)))
|
||||
.unwrap_or_default();
|
||||
let val = META_VAL_KEYS
|
||||
.iter()
|
||||
.find_map(|k| obj.get(*k))
|
||||
.map(|v| meta_text(v))
|
||||
.unwrap_or_default();
|
||||
if !key.is_empty() {
|
||||
out.insert(key, json!(val));
|
||||
}
|
||||
}
|
||||
}
|
||||
Value::Object(m) => {
|
||||
for (k, v) in m {
|
||||
out.insert(k.clone(), json!(meta_text(v)));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn meta_text(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(),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user