release: v0.3.1 — W8 favicon/head/images + entry_dir fix
Ship site icons, head asset tables, and image assembly; absolutize entry_dir for relative entry scripts so sqlite paths no longer nest. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
1e5e6f4891
commit
416914a346
29 files changed
+1497
-36
No files matched your search
@@ -0,0 +1,490 @@
|
||||
//! Site icons, `<head>` link/script assembly, and image HTML assembly.
|
||||
//! Tables stay data; assembly is a function — 配置即数据、装配即函数.
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::table::normalize_ref;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct HeadLink {
|
||||
pub rel: String,
|
||||
pub href: String,
|
||||
pub type_: String,
|
||||
pub sizes: String,
|
||||
pub media: String,
|
||||
pub as_: String,
|
||||
pub crossorigin: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct IconRoute {
|
||||
pub url: String,
|
||||
pub path: PathBuf,
|
||||
pub content_type: String,
|
||||
}
|
||||
|
||||
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 Map<String, Value>, keys: &[&str]) -> Option<&'a Value> {
|
||||
keys.iter().find_map(|k| m.get(*k))
|
||||
}
|
||||
|
||||
fn row_str(m: &Map<String, Value>, keys: &[&str]) -> String {
|
||||
pick(m, keys)
|
||||
.map(|v| normalize_ref(&cell_str(v)))
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn esc(s: &str) -> String {
|
||||
s.replace('&', "&")
|
||||
.replace('<', "<")
|
||||
.replace('>', ">")
|
||||
.replace('"', """)
|
||||
}
|
||||
|
||||
/// Infer Content-Type from file extension.
|
||||
pub fn mime_for_path(path: &str) -> &'static str {
|
||||
let lower = path.to_ascii_lowercase();
|
||||
if lower.ends_with(".ico") {
|
||||
"image/x-icon"
|
||||
} else if lower.ends_with(".png") {
|
||||
"image/png"
|
||||
} else if lower.ends_with(".svg") {
|
||||
"image/svg+xml"
|
||||
} else if lower.ends_with(".webp") {
|
||||
"image/webp"
|
||||
} else if lower.ends_with(".jpg") || lower.ends_with(".jpeg") {
|
||||
"image/jpeg"
|
||||
} else if lower.ends_with(".gif") {
|
||||
"image/gif"
|
||||
} else if lower.ends_with(".webmanifest") || lower.ends_with(".json") {
|
||||
"application/manifest+json"
|
||||
} else if lower.ends_with(".css") {
|
||||
"text/css; charset=utf-8"
|
||||
} else if lower.ends_with(".js") || lower.ends_with(".mjs") {
|
||||
"text/javascript; charset=utf-8"
|
||||
} else {
|
||||
"application/octet-stream"
|
||||
}
|
||||
}
|
||||
|
||||
fn rows_of(table: &Value) -> Vec<Map<String, Value>> {
|
||||
match table {
|
||||
Value::Array(a) => a
|
||||
.iter()
|
||||
.filter_map(|v| v.as_object().cloned())
|
||||
.collect(),
|
||||
Value::Object(m) => {
|
||||
// Columnar GFM: { 关系: […], 地址: […] }
|
||||
let keys: Vec<String> = m.keys().cloned().collect();
|
||||
if keys.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let len = m
|
||||
.values()
|
||||
.filter_map(|v| v.as_array().map(|a| a.len()))
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
if len == 0 {
|
||||
return vec![m.clone()];
|
||||
}
|
||||
let mut out = Vec::with_capacity(len);
|
||||
for i in 0..len {
|
||||
let mut row = Map::new();
|
||||
for k in &keys {
|
||||
if let Some(Value::Array(a)) = m.get(k) {
|
||||
row.insert(k.clone(), a.get(i).cloned().unwrap_or(Value::Null));
|
||||
} else if i == 0 {
|
||||
row.insert(k.clone(), m.get(k).cloned().unwrap_or(Value::Null));
|
||||
}
|
||||
}
|
||||
out.push(row);
|
||||
}
|
||||
out
|
||||
}
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalize a Head resource table → list of HeadLink.
|
||||
pub fn as_head_links(table: &Value) -> Vec<HeadLink> {
|
||||
let mut out = Vec::new();
|
||||
for m in rows_of(table) {
|
||||
let rel = row_str(&m, &["关系", "rel", "Rel"]);
|
||||
let href = row_str(
|
||||
&m,
|
||||
&["地址", "href", "src", "url", "Href", "Src", "URL"],
|
||||
);
|
||||
if href.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let rel = if rel.is_empty() {
|
||||
"stylesheet".into()
|
||||
} else {
|
||||
rel
|
||||
};
|
||||
out.push(HeadLink {
|
||||
rel,
|
||||
href,
|
||||
type_: row_str(&m, &["类型", "type", "Type"]),
|
||||
sizes: row_str(&m, &["尺寸", "sizes", "Sizes"]),
|
||||
media: row_str(&m, &["媒体", "media", "Media"]),
|
||||
as_: row_str(&m, &["作为", "as", "As"]),
|
||||
crossorigin: row_str(&m, &["跨域", "crossorigin", "crossOrigin"]),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn head_links_to_json(links: &[HeadLink]) -> Value {
|
||||
Value::Array(
|
||||
links
|
||||
.iter()
|
||||
.map(|l| {
|
||||
json!({
|
||||
"rel": l.rel,
|
||||
"href": l.href,
|
||||
"type": l.type_,
|
||||
"sizes": l.sizes,
|
||||
"media": l.media,
|
||||
"as": l.as_,
|
||||
"crossorigin": l.crossorigin,
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn head_links_from_json(v: &Value) -> Vec<HeadLink> {
|
||||
let Some(arr) = v.as_array() else {
|
||||
return as_head_links(v);
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for item in arr {
|
||||
let Some(m) = item.as_object() else {
|
||||
continue;
|
||||
};
|
||||
let href = row_str(m, &["href", "src", "url", "地址"]);
|
||||
if href.is_empty() {
|
||||
continue;
|
||||
}
|
||||
out.push(HeadLink {
|
||||
rel: row_str(m, &["rel", "关系"]),
|
||||
href,
|
||||
type_: row_str(m, &["type", "类型"]),
|
||||
sizes: row_str(m, &["sizes", "尺寸"]),
|
||||
media: row_str(m, &["media", "媒体"]),
|
||||
as_: row_str(m, &["as", "作为"]),
|
||||
crossorigin: row_str(m, &["crossorigin", "跨域"]),
|
||||
});
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Render HeadLink list to HTML (link / script tags).
|
||||
pub fn render_head_links(links: &[HeadLink]) -> String {
|
||||
let mut s = String::new();
|
||||
for l in links {
|
||||
let rel = l.rel.trim().to_ascii_lowercase();
|
||||
if rel == "script" || rel == "module" {
|
||||
let mut tag = String::from("<script");
|
||||
if rel == "module" || l.type_ == "module" {
|
||||
tag.push_str(" type=\"module\"");
|
||||
} else if !l.type_.is_empty() {
|
||||
tag.push_str(&format!(" type=\"{}\"", esc(&l.type_)));
|
||||
}
|
||||
if !l.crossorigin.is_empty() {
|
||||
tag.push_str(&format!(" crossorigin=\"{}\"", esc(&l.crossorigin)));
|
||||
}
|
||||
tag.push_str(&format!(" src=\"{}\"></script>", esc(&l.href)));
|
||||
s.push_str(&tag);
|
||||
continue;
|
||||
}
|
||||
let mut tag = format!("<link rel=\"{}\" href=\"{}\"", esc(&l.rel), esc(&l.href));
|
||||
if !l.type_.is_empty() {
|
||||
tag.push_str(&format!(" type=\"{}\"", esc(&l.type_)));
|
||||
}
|
||||
if !l.sizes.is_empty() {
|
||||
tag.push_str(&format!(" sizes=\"{}\"", esc(&l.sizes)));
|
||||
}
|
||||
if !l.media.is_empty() {
|
||||
tag.push_str(&format!(" media=\"{}\"", esc(&l.media)));
|
||||
}
|
||||
if !l.as_.is_empty() {
|
||||
tag.push_str(&format!(" as=\"{}\"", esc(&l.as_)));
|
||||
}
|
||||
if !l.crossorigin.is_empty() {
|
||||
tag.push_str(&format!(" crossorigin=\"{}\"", esc(&l.crossorigin)));
|
||||
}
|
||||
tag.push_str("/>");
|
||||
s.push_str(&tag);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Module-level preview: assemble head table → HTML string.
|
||||
pub fn make_head_html(table: &Value) -> String {
|
||||
render_head_links(&as_head_links(table))
|
||||
}
|
||||
|
||||
/// Normalize icons table → (icons json array, site_head links, file routes).
|
||||
pub fn normalize_icons(table: &Value) -> (Value, Vec<HeadLink>, Vec<IconRoute>) {
|
||||
let mut icons = Vec::new();
|
||||
let mut head = Vec::new();
|
||||
let mut routes = Vec::new();
|
||||
let mut saw_favicon_url = false;
|
||||
|
||||
for m in rows_of(table) {
|
||||
let path = row_str(&m, &["路径", "path", "file", "Path"]);
|
||||
let mut rel = row_str(&m, &["关系", "rel", "Rel"]);
|
||||
if rel.is_empty() {
|
||||
rel = "icon".into();
|
||||
}
|
||||
let mut type_ = row_str(&m, &["类型", "type", "Type"]);
|
||||
let sizes = row_str(&m, &["尺寸", "sizes", "Sizes"]);
|
||||
let mut url = row_str(&m, &["地址", "url", "href", "Href", "URL"]);
|
||||
|
||||
if type_.is_empty() && !path.is_empty() {
|
||||
type_ = mime_for_path(&path).to_string();
|
||||
}
|
||||
if url.is_empty() {
|
||||
if !path.is_empty() {
|
||||
let name = Path::new(&path)
|
||||
.file_name()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("icon");
|
||||
let lower = path.to_ascii_lowercase();
|
||||
if rel.to_ascii_lowercase().contains("icon") && lower.ends_with(".ico") {
|
||||
url = "/favicon.ico".into();
|
||||
} else {
|
||||
url = format!("/icons/{name}");
|
||||
}
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if url == "/favicon.ico" {
|
||||
saw_favicon_url = true;
|
||||
}
|
||||
|
||||
icons.push(json!({
|
||||
"path": path,
|
||||
"rel": rel,
|
||||
"type": type_,
|
||||
"sizes": sizes,
|
||||
"url": url,
|
||||
}));
|
||||
|
||||
if !url.is_empty() {
|
||||
head.push(HeadLink {
|
||||
rel: rel.clone(),
|
||||
href: url.clone(),
|
||||
type_: type_.clone(),
|
||||
sizes: sizes.clone(),
|
||||
media: String::new(),
|
||||
as_: String::new(),
|
||||
crossorigin: String::new(),
|
||||
});
|
||||
}
|
||||
|
||||
if !path.is_empty() && !url.is_empty() {
|
||||
routes.push(IconRoute {
|
||||
url: url.clone(),
|
||||
path: PathBuf::from(&path),
|
||||
content_type: if type_.is_empty() {
|
||||
mime_for_path(&path).to_string()
|
||||
} else {
|
||||
type_.clone()
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure browser default path if we have an icon file but no /favicon.ico.
|
||||
if !saw_favicon_url {
|
||||
if let Some(first) = icons.iter().find(|v| {
|
||||
v.get("rel")
|
||||
.and_then(|r| r.as_str())
|
||||
.map(|r| r.to_ascii_lowercase().contains("icon"))
|
||||
.unwrap_or(false)
|
||||
&& v.get("path")
|
||||
.and_then(|p| p.as_str())
|
||||
.map(|p| !p.is_empty())
|
||||
.unwrap_or(false)
|
||||
}) {
|
||||
let path = first.get("path").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let type_ = first
|
||||
.get("type")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or_else(|| mime_for_path(path));
|
||||
routes.push(IconRoute {
|
||||
url: "/favicon.ico".into(),
|
||||
path: PathBuf::from(path),
|
||||
content_type: type_.to_string(),
|
||||
});
|
||||
head.insert(
|
||||
0,
|
||||
HeadLink {
|
||||
rel: "icon".into(),
|
||||
href: "/favicon.ico".into(),
|
||||
type_: type_.to_string(),
|
||||
sizes: first
|
||||
.get("sizes")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string(),
|
||||
media: String::new(),
|
||||
as_: String::new(),
|
||||
crossorigin: String::new(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
(Value::Array(icons), head, routes)
|
||||
}
|
||||
|
||||
/// Convention: if static_dir has favicon.ico|png|svg and icons empty, register defaults.
|
||||
pub fn convention_favicon(static_dir: &Path) -> Option<(Vec<HeadLink>, Vec<IconRoute>)> {
|
||||
for name in ["favicon.ico", "favicon.png", "favicon.svg"] {
|
||||
let p = static_dir.join(name);
|
||||
if p.is_file() {
|
||||
let ct = mime_for_path(name).to_string();
|
||||
let head = vec![HeadLink {
|
||||
rel: "icon".into(),
|
||||
href: "/favicon.ico".into(),
|
||||
type_: ct.clone(),
|
||||
sizes: String::new(),
|
||||
media: String::new(),
|
||||
as_: String::new(),
|
||||
crossorigin: String::new(),
|
||||
}];
|
||||
let routes = vec![IconRoute {
|
||||
url: "/favicon.ico".into(),
|
||||
path: p,
|
||||
content_type: ct,
|
||||
}];
|
||||
return Some((head, routes));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Merge site_head into a page value (dedupe by href+rel).
|
||||
pub fn merge_site_head(page: &mut Value, site_head: &[HeadLink]) {
|
||||
if site_head.is_empty() {
|
||||
return;
|
||||
}
|
||||
let obj = match page.as_object_mut() {
|
||||
Some(o) => o,
|
||||
None => return,
|
||||
};
|
||||
let mut existing = obj
|
||||
.get("head")
|
||||
.map(head_links_from_json)
|
||||
.unwrap_or_default();
|
||||
for link in site_head {
|
||||
let dup = existing.iter().any(|e| {
|
||||
e.href == link.href && e.rel.eq_ignore_ascii_case(&link.rel)
|
||||
});
|
||||
if !dup {
|
||||
existing.push(link.clone());
|
||||
}
|
||||
}
|
||||
obj.insert("head".into(), head_links_to_json(&existing));
|
||||
}
|
||||
|
||||
/// GFM image table → HTML fragment.
|
||||
pub fn make_images_html(table: &Value) -> String {
|
||||
let mut figures = String::new();
|
||||
for m in rows_of(table) {
|
||||
let src = row_str(&m, &["源", "src", "Src", "url", "URL"]);
|
||||
if src.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let alt = row_str(&m, &["替代", "alt", "Alt"]);
|
||||
let title = row_str(&m, &["标题", "title", "Title"]);
|
||||
let class = row_str(&m, &["类", "class", "Class"]);
|
||||
let href = row_str(&m, &["链接", "href", "link", "Href", "Link"]);
|
||||
let width = row_str(&m, &["宽度", "width", "Width"]);
|
||||
let height = row_str(&m, &["高度", "height", "Height"]);
|
||||
let mut loading = row_str(&m, &["加载", "loading", "Loading"]);
|
||||
if loading.is_empty() {
|
||||
loading = "lazy".into();
|
||||
}
|
||||
let caption = row_str(&m, &["图注", "caption", "Caption"]);
|
||||
|
||||
let mut img = format!("<img src=\"{}\" alt=\"{}\"", esc(&src), esc(&alt));
|
||||
if !title.is_empty() {
|
||||
img.push_str(&format!(" title=\"{}\"", esc(&title)));
|
||||
}
|
||||
if !width.is_empty() {
|
||||
img.push_str(&format!(" width=\"{}\"", esc(&width)));
|
||||
}
|
||||
if !height.is_empty() {
|
||||
img.push_str(&format!(" height=\"{}\"", esc(&height)));
|
||||
}
|
||||
img.push_str(&format!(" loading=\"{}\"/>", esc(&loading)));
|
||||
|
||||
let inner = if href.is_empty() {
|
||||
img
|
||||
} else {
|
||||
format!("<a href=\"{}\">{}</a>", esc(&href), img)
|
||||
};
|
||||
|
||||
let fig_class = if class.is_empty() {
|
||||
"mq-img".into()
|
||||
} else {
|
||||
format!("mq-img {}", class)
|
||||
};
|
||||
figures.push_str(&format!("<figure class=\"{}\">{}", fig_class, inner));
|
||||
if !caption.is_empty() {
|
||||
figures.push_str(&format!("<figcaption>{}</figcaption>", esc(&caption)));
|
||||
}
|
||||
figures.push_str("</figure>");
|
||||
}
|
||||
if figures.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
format!("<div class=\"mq-images\" data-slot=\"main\">{figures}</div>")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn images_basic() {
|
||||
let t = json!([
|
||||
{"源": "/a.png", "替代": "A", "类": "logo", "加载": "eager"}
|
||||
]);
|
||||
let h = make_images_html(&t);
|
||||
assert!(h.contains("mq-images"));
|
||||
assert!(h.contains("src=\"/a.png\""));
|
||||
assert!(h.contains("loading=\"eager\""));
|
||||
assert!(h.contains("class=\"mq-img logo\""));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn head_script_and_icon() {
|
||||
let t = json!([
|
||||
{"关系": "icon", "地址": "/favicon.ico", "类型": "image/x-icon"},
|
||||
{"关系": "script", "地址": "/static/a.js"}
|
||||
]);
|
||||
let h = make_head_html(&t);
|
||||
assert!(h.contains("rel=\"icon\""));
|
||||
assert!(h.contains("<script src=\"/static/a.js\"></script>"));
|
||||
}
|
||||
}
|
||||
+86
-4
@@ -26,6 +26,34 @@ use crate::sitemap;
|
||||
use crate::storage;
|
||||
use crate::upload;
|
||||
|
||||
fn with_site_head(base: &Value, site_head: &[crate::assets::HeadLink]) -> Value {
|
||||
let mut page = base.clone();
|
||||
crate::assets::merge_site_head(&mut page, site_head);
|
||||
page
|
||||
}
|
||||
|
||||
fn serve_icon_file(path: PathBuf, content_type: String) -> Response {
|
||||
match std::fs::read(&path) {
|
||||
Ok(bytes) => {
|
||||
let ct = HeaderValue::from_str(&content_type)
|
||||
.unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream"));
|
||||
(
|
||||
StatusCode::OK,
|
||||
[
|
||||
(header::CONTENT_TYPE, ct),
|
||||
(
|
||||
header::CACHE_CONTROL,
|
||||
HeaderValue::from_static("public, max-age=86400"),
|
||||
),
|
||||
],
|
||||
bytes,
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
Err(_) => StatusCode::NOT_FOUND.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct UploadRoute {
|
||||
pub field: String,
|
||||
@@ -58,6 +86,8 @@ pub struct AppState {
|
||||
/// Optional assembled pages for 404 / 500.
|
||||
page_404: Option<Value>,
|
||||
page_500: Option<Value>,
|
||||
/// Default `<head>` links from `app.icons` / static favicon convention.
|
||||
site_head: Vec<crate::assets::HeadLink>,
|
||||
}
|
||||
|
||||
fn collect_page_forms(
|
||||
@@ -107,6 +137,8 @@ pub fn listen(
|
||||
gates: Vec<(String, Vec<String>)>,
|
||||
gallery_routes: HashMap<String, Value>,
|
||||
middleware: &Middleware,
|
||||
mut site_head: Vec<crate::assets::HeadLink>,
|
||||
mut icon_routes: Vec<crate::assets::IconRoute>,
|
||||
) -> Result<Value, String> {
|
||||
let mut form_owners = HashMap::new();
|
||||
collect_page_forms(page, &mut forms, &mut form_owners);
|
||||
@@ -120,6 +152,20 @@ pub fn listen(
|
||||
});
|
||||
session::reset(session_ttl);
|
||||
rate_limit::reset();
|
||||
|
||||
// Convention: static_dir/favicon.* → /favicon.ico when no explicit icons.
|
||||
if icon_routes.is_empty() {
|
||||
if let Some(dir) = static_dir.as_ref() {
|
||||
if let Some((head, routes)) = crate::assets::convention_favicon(dir) {
|
||||
site_head = head;
|
||||
icon_routes = routes;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve relative icon paths: try as-is absolute, else leave for entry_dir resolve in lib.
|
||||
// (Absolute paths preferred; relative already joined in web_listen.)
|
||||
|
||||
let state = Arc::new(AppState {
|
||||
page: page.clone(),
|
||||
db_url: db_url.map(|s| s.to_string()),
|
||||
@@ -133,6 +179,7 @@ pub fn listen(
|
||||
download_routes: download_routes.clone(),
|
||||
page_404: page_404.clone(),
|
||||
page_500: page_500.clone(),
|
||||
site_head: site_head.clone(),
|
||||
});
|
||||
|
||||
let mut app = Router::new()
|
||||
@@ -165,6 +212,7 @@ pub fn listen(
|
||||
get(async move |State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap, Path(params): Path<HashMap<String, String>>| {
|
||||
let mut p = page_for_render.clone();
|
||||
inject_params(&mut p, ¶ms);
|
||||
let p = with_site_head(&p, &st.site_head);
|
||||
let (_, csrf, set_cookie) = resolve_session(&headers);
|
||||
let mut resp = Html(render::render_page(&p, st.db_url.as_deref(), Some(&csrf))).into_response();
|
||||
append_set_cookie(&mut resp, set_cookie);
|
||||
@@ -188,7 +236,8 @@ pub fn listen(
|
||||
&path,
|
||||
get(async move |State(st): State<Arc<AppState>>, headers: axum::http::HeaderMap| {
|
||||
let (_, csrf, set_cookie) = resolve_session(&headers);
|
||||
let mut resp = Html(render::render_page(&page_for_render, st.db_url.as_deref(), Some(&csrf)))
|
||||
let p = with_site_head(&page_for_render, &st.site_head);
|
||||
let mut resp = Html(render::render_page(&p, st.db_url.as_deref(), Some(&csrf)))
|
||||
.into_response();
|
||||
append_set_cookie(&mut resp, set_cookie);
|
||||
resp
|
||||
@@ -293,6 +342,36 @@ pub fn listen(
|
||||
app = app.nest_service(&mount, svc);
|
||||
}
|
||||
|
||||
// Root / custom icon file routes (favicon.ico, /icons/…).
|
||||
for ir in icon_routes {
|
||||
let url = ir.url.clone();
|
||||
if !url.starts_with('/') {
|
||||
return Err(format!("icon url `{url}` must start with /"));
|
||||
}
|
||||
if !ir.path.is_file() {
|
||||
return Err(format!(
|
||||
"icon file `{}` not found for `{url}`",
|
||||
ir.path.display()
|
||||
));
|
||||
}
|
||||
eprintln!(
|
||||
"marqdo web icon: {} → {} ({})",
|
||||
url,
|
||||
ir.path.display(),
|
||||
ir.content_type
|
||||
);
|
||||
let path = ir.path.clone();
|
||||
let ct = ir.content_type.clone();
|
||||
app = app.route(
|
||||
&url,
|
||||
get(move || {
|
||||
let path = path.clone();
|
||||
let ct = ct.clone();
|
||||
async move { serve_icon_file(path, ct) }
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
let mut redir_paths: Vec<String> = redirects.keys().cloned().collect();
|
||||
redir_paths.sort();
|
||||
for path in redir_paths {
|
||||
@@ -435,7 +514,8 @@ fn rss_feed(st: &AppState, _path: &str, cfg: &Value) -> 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));
|
||||
let page = with_site_head(&st.page, &st.site_head);
|
||||
let html = render::render_page(&page, st.db_url.as_deref(), Some(&csrf));
|
||||
let mut resp = Html(html).into_response();
|
||||
append_set_cookie(&mut resp, set_cookie);
|
||||
resp
|
||||
@@ -1638,7 +1718,8 @@ fn sitemap_response(st: &AppState, cfg: &Value) -> 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))
|
||||
let page = with_site_head(page, &st.site_head);
|
||||
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()
|
||||
@@ -1652,7 +1733,8 @@ async fn fallback_404(State(st): State<Arc<AppState>>, headers: axum::http::Head
|
||||
#[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)
|
||||
let page = with_site_head(page, &st.site_head);
|
||||
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>",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Marqdo web plugin (C ABI v2): SQLite, page assemble, HTTP listen.
|
||||
|
||||
mod assets;
|
||||
mod compose;
|
||||
mod db;
|
||||
mod db_pg;
|
||||
@@ -373,6 +374,93 @@ web_ffi!(web_page_meta, |args: &Value| {
|
||||
Ok(Value::Object(obj))
|
||||
});
|
||||
|
||||
web_ffi!(web_page_head, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let table = args
|
||||
.get("table")
|
||||
.or_else(|| args.get("head"))
|
||||
.cloned()
|
||||
.unwrap_or(json!([]));
|
||||
let links = crate::assets::as_head_links(&table);
|
||||
let mut obj = page.as_object().cloned().unwrap_or_default();
|
||||
let mut existing = obj
|
||||
.get("head")
|
||||
.map(crate::assets::head_links_from_json)
|
||||
.unwrap_or_default();
|
||||
for link in links {
|
||||
let dup = existing
|
||||
.iter()
|
||||
.any(|e| e.href == link.href && e.rel.eq_ignore_ascii_case(&link.rel));
|
||||
if !dup {
|
||||
existing.push(link);
|
||||
}
|
||||
}
|
||||
obj.insert("head".into(), crate::assets::head_links_to_json(&existing));
|
||||
Ok(Value::Object(obj))
|
||||
});
|
||||
|
||||
web_ffi!(web_head, |args: &Value| {
|
||||
let table = args
|
||||
.get("table")
|
||||
.or_else(|| args.get("head"))
|
||||
.cloned()
|
||||
.unwrap_or(json!([]));
|
||||
Ok(Value::String(crate::assets::make_head_html(&table)))
|
||||
});
|
||||
|
||||
web_ffi!(web_images, |args: &Value| {
|
||||
let table = args
|
||||
.get("table")
|
||||
.or_else(|| args.get("images"))
|
||||
.cloned()
|
||||
.unwrap_or(json!([]));
|
||||
Ok(Value::String(crate::assets::make_images_html(&table)))
|
||||
});
|
||||
|
||||
web_ffi!(web_page_images, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let table = args
|
||||
.get("table")
|
||||
.or_else(|| args.get("images"))
|
||||
.cloned()
|
||||
.unwrap_or(json!([]));
|
||||
let html = crate::assets::make_images_html(&table);
|
||||
let mut obj = page.as_object().cloned().unwrap_or_default();
|
||||
let prev = obj
|
||||
.get("images_html")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let combined = if prev.is_empty() {
|
||||
html
|
||||
} else if html.is_empty() {
|
||||
prev
|
||||
} else {
|
||||
format!("{prev}{html}")
|
||||
};
|
||||
obj.insert("images_html".into(), json!(combined));
|
||||
Ok(Value::Object(obj))
|
||||
});
|
||||
|
||||
web_ffi!(web_app_icons, |args: &Value| {
|
||||
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
||||
let table = args
|
||||
.get("table")
|
||||
.or_else(|| args.get("icons"))
|
||||
.cloned()
|
||||
.unwrap_or(json!([]));
|
||||
let (icons, site_head, _routes) = crate::assets::normalize_icons(&table);
|
||||
let obj = app
|
||||
.as_object_mut()
|
||||
.ok_or_else(|| "app must be a map".to_string())?;
|
||||
obj.insert("icons".into(), icons);
|
||||
obj.insert(
|
||||
"site_head".into(),
|
||||
crate::assets::head_links_to_json(&site_head),
|
||||
);
|
||||
Ok(app)
|
||||
});
|
||||
|
||||
web_ffi!(web_page_paginate, |args: &Value| {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let offset = args
|
||||
@@ -1424,6 +1512,8 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
gallery_routes,
|
||||
middleware,
|
||||
cookie_secure,
|
||||
site_head,
|
||||
icon_routes,
|
||||
) = if args.get("page").is_some() || args.get("host").is_some() {
|
||||
let page = args.get("page").cloned().unwrap_or(json!({}));
|
||||
let db_url = db_url_of(args).ok();
|
||||
@@ -1478,6 +1568,8 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
HashMap::new(),
|
||||
middleware::Middleware::default(),
|
||||
cookie_secure,
|
||||
Vec::<crate::assets::HeadLink>::new(),
|
||||
Vec::<crate::assets::IconRoute>::new(),
|
||||
)
|
||||
} else {
|
||||
let app = args.get("app").cloned().unwrap_or_else(|| args.clone());
|
||||
@@ -1684,6 +1776,20 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
.get("cookie_secure")
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
let (site_head, icon_routes) = if let Some(icons) = app.get("icons") {
|
||||
let (_icons_json, head, routes) = crate::assets::normalize_icons(icons);
|
||||
// Prefer precomputed site_head if present (same content).
|
||||
let head = app
|
||||
.get("site_head")
|
||||
.map(crate::assets::head_links_from_json)
|
||||
.filter(|h| !h.is_empty())
|
||||
.unwrap_or(head);
|
||||
(head, routes)
|
||||
} else if let Some(sh) = app.get("site_head") {
|
||||
(crate::assets::head_links_from_json(sh), Vec::new())
|
||||
} else {
|
||||
(Vec::new(), Vec::new())
|
||||
};
|
||||
(
|
||||
page,
|
||||
db_url,
|
||||
@@ -1709,6 +1815,8 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
gallery_routes,
|
||||
middleware,
|
||||
cookie_secure,
|
||||
site_head,
|
||||
icon_routes,
|
||||
)
|
||||
};
|
||||
let static_dir = static_dir.map(|p| {
|
||||
@@ -1718,6 +1826,32 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
entry_dir().join(p)
|
||||
}
|
||||
});
|
||||
let icon_routes: Vec<crate::assets::IconRoute> = icon_routes
|
||||
.into_iter()
|
||||
.map(|mut r| {
|
||||
if !r.path.is_absolute() {
|
||||
let joined = entry_dir().join(&r.path);
|
||||
if joined.is_file() {
|
||||
r.path = joined;
|
||||
} else if let Some(ref sd) = static_dir {
|
||||
let name = r
|
||||
.path
|
||||
.file_name()
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| r.path.clone());
|
||||
let in_static = sd.join(&name);
|
||||
if in_static.is_file() {
|
||||
r.path = in_static;
|
||||
} else {
|
||||
r.path = joined;
|
||||
}
|
||||
} else {
|
||||
r.path = joined;
|
||||
}
|
||||
}
|
||||
r
|
||||
})
|
||||
.collect();
|
||||
http::listen(
|
||||
&page,
|
||||
db_url.as_deref(),
|
||||
@@ -1743,6 +1877,8 @@ web_ffi!(web_listen, |args: &Value| {
|
||||
gates,
|
||||
gallery_routes,
|
||||
&middleware,
|
||||
site_head,
|
||||
icon_routes,
|
||||
)
|
||||
});
|
||||
|
||||
@@ -1816,6 +1952,23 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
|
||||
"page,meta",
|
||||
web_page_meta as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_page_head",
|
||||
"page,table",
|
||||
web_page_head as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_page_images",
|
||||
"page,table",
|
||||
web_page_images as PluginFn,
|
||||
),
|
||||
("web_head", "table", web_head as PluginFn),
|
||||
("web_images", "table", web_images as PluginFn),
|
||||
(
|
||||
"web_app_icons",
|
||||
"app,table",
|
||||
web_app_icons as PluginFn,
|
||||
),
|
||||
(
|
||||
"web_page_paginate",
|
||||
"page,offset,limit,path",
|
||||
|
||||
@@ -376,6 +376,18 @@ fn head_html(args: &Value, default_title: &str) -> String {
|
||||
"canonical" => {
|
||||
s.push_str(&format!("<link rel=\"canonical\" href=\"{}\"/>", esc(&val)));
|
||||
}
|
||||
"icon" | "favicon" => {
|
||||
s.push_str(&format!(
|
||||
"<link rel=\"icon\" href=\"{}\"/>",
|
||||
esc(&val)
|
||||
));
|
||||
}
|
||||
"apple-touch-icon" | "apple_touch_icon" => {
|
||||
s.push_str(&format!(
|
||||
"<link rel=\"apple-touch-icon\" href=\"{}\"/>",
|
||||
esc(&val)
|
||||
));
|
||||
}
|
||||
k if k.starts_with("og:") => {
|
||||
s.push_str(&format!(
|
||||
"<meta property=\"{}\" content=\"{}\"/>",
|
||||
@@ -393,6 +405,10 @@ fn head_html(args: &Value, default_title: &str) -> String {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(head) = args.get("head") {
|
||||
let links = crate::assets::head_links_from_json(head);
|
||||
s.push_str(&crate::assets::render_head_links(&links));
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
@@ -476,6 +492,11 @@ pub fn render_page_ex(
|
||||
};
|
||||
|
||||
let mut main_html = String::new();
|
||||
if let Some(images) = args.get("images_html").and_then(|v| v.as_str()) {
|
||||
if !images.is_empty() {
|
||||
main_html.push_str(images);
|
||||
}
|
||||
}
|
||||
if !intro.is_empty() {
|
||||
main_html.push_str(&format!("<div class=\"main-intro\">{intro}</div>"));
|
||||
}
|
||||
@@ -579,6 +600,11 @@ pub fn render_fragment(args: &Value, db_url: Option<&str>) -> String {
|
||||
_ => {
|
||||
let (intro, items, _total) = resolve_main(args, db_url);
|
||||
let mut body = String::new();
|
||||
if let Some(images) = args.get("images_html").and_then(|v| v.as_str()) {
|
||||
if !images.is_empty() {
|
||||
body.push_str(images);
|
||||
}
|
||||
}
|
||||
if !intro.is_empty() {
|
||||
body.push_str(&format!("<div class=\"main-intro\">{intro}</div>"));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user