Add the network-extension wave to lib/net and the web ABI plugin:
- lib/net cookie_parse / multipart_parse host primitives (EN/ZH)
- plugins/web session store + /admin login gate + WebSocket client/server
- ext/web author surface (EN/ZH) for session, auth, ws
- form update flow and page-level validation echo tests
- fix string escapes: \xHH, \u{...}, unknown escapes kept verbatim
- map Chinese component slots (导航/侧栏/页脚) so sidebar renders
- resolve relative static/db paths against the entry script dir (entry_dir)
- new tutorial chapter 14, EN/ZH example sites, and gold tests
Co-authored-by: Cursor <cursoragent@cursor.com>
980 lines
30 KiB
Rust
980 lines
30 KiB
Rust
//! Marqdo web plugin (C ABI v2): SQLite, page assemble, HTTP listen.
|
|
|
|
mod compose;
|
|
mod db;
|
|
mod form;
|
|
mod http;
|
|
mod render;
|
|
mod session;
|
|
mod table;
|
|
mod ws;
|
|
|
|
use std::ffi::{CStr, CString};
|
|
use std::os::raw::{c_char, c_int, c_void};
|
|
use std::path::PathBuf;
|
|
use std::ptr;
|
|
|
|
use serde_json::{json, Value};
|
|
|
|
const ABI_VERSION: u32 = 2;
|
|
|
|
type PluginFn = unsafe extern "C" fn(
|
|
args_json: *const c_char,
|
|
out_json: *mut *mut c_char,
|
|
err_msg: *mut *mut c_char,
|
|
) -> c_int;
|
|
|
|
type HostQueryFn = unsafe extern "C" fn(
|
|
userdata: *mut c_void,
|
|
name: *const c_char,
|
|
args_json: *const c_char,
|
|
out_json: *mut *mut c_char,
|
|
err_msg: *mut *mut c_char,
|
|
) -> c_int;
|
|
|
|
#[repr(C)]
|
|
pub struct MarqdoHostApi {
|
|
pub userdata: *mut c_void,
|
|
pub register_fn: Option<
|
|
unsafe extern "C" fn(
|
|
userdata: *mut c_void,
|
|
name: *const c_char,
|
|
params: *const c_char,
|
|
fn_ptr: PluginFn,
|
|
) -> c_int,
|
|
>,
|
|
pub alloc: Option<unsafe extern "C" fn(n: usize) -> *mut c_void>,
|
|
pub free: Option<unsafe extern "C" fn(p: *mut c_void)>,
|
|
pub host_query: Option<HostQueryFn>,
|
|
}
|
|
|
|
static mut HOST_FREE: Option<unsafe extern "C" fn(*mut c_void)> = None;
|
|
static mut HOST_ALLOC: Option<unsafe extern "C" fn(usize) -> *mut c_void> = None;
|
|
static mut HOST_QUERY: Option<HostQueryFn> = None;
|
|
static mut HOST_USERDATA: *mut c_void = ptr::null_mut();
|
|
|
|
unsafe fn host_strdup(s: &str) -> *mut c_char {
|
|
let alloc = HOST_ALLOC.expect("host alloc");
|
|
let bytes = s.as_bytes();
|
|
let p = alloc(bytes.len() + 1) as *mut u8;
|
|
if p.is_null() {
|
|
return ptr::null_mut();
|
|
}
|
|
std::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len());
|
|
*p.add(bytes.len()) = 0;
|
|
p as *mut c_char
|
|
}
|
|
|
|
fn set_out(out: *mut *mut c_char, s: &str) {
|
|
if out.is_null() {
|
|
return;
|
|
}
|
|
unsafe {
|
|
*out = host_strdup(s);
|
|
}
|
|
}
|
|
|
|
fn set_err(err: *mut *mut c_char, s: &str) {
|
|
if err.is_null() {
|
|
return;
|
|
}
|
|
unsafe {
|
|
*err = host_strdup(s);
|
|
}
|
|
}
|
|
|
|
fn parse_args(args_json: *const c_char) -> Result<Value, String> {
|
|
if args_json.is_null() {
|
|
return Ok(json!({}));
|
|
}
|
|
let s = unsafe { CStr::from_ptr(args_json) }
|
|
.to_str()
|
|
.map_err(|_| "args not utf-8".to_string())?;
|
|
if s.trim().is_empty() {
|
|
return Ok(json!({}));
|
|
}
|
|
serde_json::from_str(s).map_err(|e| e.to_string())
|
|
}
|
|
|
|
fn take_host_string(p: *mut c_char) -> Option<String> {
|
|
if p.is_null() {
|
|
return None;
|
|
}
|
|
let s = unsafe { CStr::from_ptr(p) }
|
|
.to_str()
|
|
.ok()
|
|
.map(|s| s.to_string());
|
|
unsafe {
|
|
if let Some(free) = HOST_FREE {
|
|
free(p as *mut c_void);
|
|
}
|
|
}
|
|
s
|
|
}
|
|
|
|
fn host_query_json(name: &str, args: &Value) -> Result<Value, String> {
|
|
let query = unsafe { HOST_QUERY }.ok_or_else(|| "host_query not available".to_string())?;
|
|
let userdata = unsafe { HOST_USERDATA };
|
|
let c_name = CString::new(name).map_err(|e| e.to_string())?;
|
|
let c_args = CString::new(args.to_string()).map_err(|e| e.to_string())?;
|
|
let mut out_ptr: *mut c_char = ptr::null_mut();
|
|
let mut err_ptr: *mut c_char = ptr::null_mut();
|
|
let rc = unsafe {
|
|
query(
|
|
userdata,
|
|
c_name.as_ptr(),
|
|
c_args.as_ptr(),
|
|
&mut out_ptr,
|
|
&mut err_ptr,
|
|
)
|
|
};
|
|
let err = take_host_string(err_ptr);
|
|
let out = take_host_string(out_ptr);
|
|
if rc != 0 {
|
|
return Err(err.unwrap_or_else(|| format!("host_query `{name}` failed")));
|
|
}
|
|
let out = out.unwrap_or_else(|| "null".into());
|
|
serde_json::from_str(&out).map_err(|e| format!("host_query `{name}` bad JSON: {e}"))
|
|
}
|
|
|
|
fn call_lib(path: &str) -> Result<Value, String> {
|
|
host_query_json("call_lib_path", &json!({ "path": path }))
|
|
}
|
|
|
|
/// Absolute directory of the entry `.mq.md` (falls back to process cwd).
|
|
fn entry_dir() -> PathBuf {
|
|
host_query_json("entry_dir", &json!({}))
|
|
.ok()
|
|
.and_then(|v| v.as_str().map(|s| PathBuf::from(s)))
|
|
.unwrap_or_else(|| {
|
|
std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."))
|
|
})
|
|
}
|
|
|
|
/// `sqlite:` URL with a relative path → absolute against `entry_dir()`.
|
|
fn resolve_db_url(url: &str) -> String {
|
|
let stripped = url
|
|
.strip_prefix("sqlite:")
|
|
.or_else(|| url.strip_prefix("SQLITE:"))
|
|
.unwrap_or(url);
|
|
let abs = PathBuf::from(stripped);
|
|
let abs = if abs.is_absolute() {
|
|
abs
|
|
} else {
|
|
entry_dir().join(abs)
|
|
};
|
|
if stripped.len() == url.len() {
|
|
abs.to_string_lossy().into_owned()
|
|
} else if url.starts_with("sqlite:") {
|
|
format!("sqlite:{}", abs.to_string_lossy())
|
|
} else {
|
|
format!("SQLITE:{}", abs.to_string_lossy())
|
|
}
|
|
}
|
|
|
|
fn arg_text(v: &Value, key: &str) -> Result<String, String> {
|
|
match v.get(key) {
|
|
None | Some(Value::Null) => Err(format!("missing `{key}`")),
|
|
Some(Value::String(s)) => Ok(s.clone()),
|
|
Some(Value::Number(n)) => Ok(n.to_string()),
|
|
Some(Value::Bool(b)) => Ok(b.to_string()),
|
|
Some(other) => Ok(other.to_string()),
|
|
}
|
|
}
|
|
|
|
fn arg_str<'a>(v: &'a Value, key: &str) -> Result<&'a str, String> {
|
|
v.get(key)
|
|
.and_then(|x| x.as_str())
|
|
.ok_or_else(|| format!("missing `{key}`"))
|
|
}
|
|
|
|
fn arg_str_opt<'a>(v: &'a Value, key: &str) -> Option<&'a str> {
|
|
v.get(key).and_then(|x| x.as_str()).filter(|s| !s.is_empty())
|
|
}
|
|
|
|
fn db_url_of(args: &Value) -> Result<String, String> {
|
|
let raw = if let Some(s) = arg_str_opt(args, "url").or_else(|| arg_str_opt(args, "db_url"))
|
|
{
|
|
Some(s.to_string())
|
|
} else if let Some(db) = args.get("db") {
|
|
if let Some(s) = db.get("url").and_then(|v| v.as_str()) {
|
|
Some(s.to_string())
|
|
} else {
|
|
None
|
|
}
|
|
} else {
|
|
None
|
|
};
|
|
match raw {
|
|
Some(s) => Ok(resolve_db_url(&s)),
|
|
None => Err("missing db url".into()),
|
|
}
|
|
}
|
|
|
|
fn reply(out_json: *mut *mut c_char, err_msg: *mut *mut c_char, r: Result<Value, String>) -> c_int {
|
|
match r {
|
|
Ok(v) => {
|
|
set_out(out_json, &v.to_string());
|
|
0
|
|
}
|
|
Err(e) => {
|
|
set_err(err_msg, &e);
|
|
1
|
|
}
|
|
}
|
|
}
|
|
|
|
macro_rules! web_ffi {
|
|
($name:ident, $body:expr) => {
|
|
unsafe extern "C" fn $name(
|
|
args_json: *const c_char,
|
|
out_json: *mut *mut c_char,
|
|
err_msg: *mut *mut c_char,
|
|
) -> c_int {
|
|
let args = match parse_args(args_json) {
|
|
Ok(v) => v,
|
|
Err(e) => {
|
|
set_err(err_msg, &format!("{}: {e}", stringify!($name)));
|
|
return 1;
|
|
}
|
|
};
|
|
let r: Result<Value, String> = (|| $body(&args))();
|
|
reply(
|
|
out_json,
|
|
err_msg,
|
|
r.map_err(|e| format!("{}: {e}", stringify!($name))),
|
|
)
|
|
}
|
|
};
|
|
}
|
|
|
|
web_ffi!(web_page_new, |args: &Value| {
|
|
let title = arg_str_opt(args, "title").unwrap_or("Marqdo Web");
|
|
let intro = arg_str_opt(args, "intro").unwrap_or("");
|
|
Ok(json!({
|
|
"title": title,
|
|
"intro": intro,
|
|
}))
|
|
});
|
|
|
|
web_ffi!(web_compose_components, |args: &Value| {
|
|
let page = args.get("page").cloned().unwrap_or(json!({}));
|
|
let components = args
|
|
.get("components")
|
|
.cloned()
|
|
.ok_or_else(|| "missing `components`".to_string())?;
|
|
compose::compose_components(&page, &components, |path| call_lib(path))
|
|
});
|
|
|
|
web_ffi!(web_compose_main, |args: &Value| {
|
|
let page = args.get("page").cloned().unwrap_or(json!({}));
|
|
let main = args
|
|
.get("main")
|
|
.cloned()
|
|
.ok_or_else(|| "missing `main`".to_string())?;
|
|
compose::compose_main(&page, &main, |path| call_lib(path))
|
|
});
|
|
|
|
web_ffi!(web_compose_form, |args: &Value| {
|
|
let page = args.get("page").cloned().unwrap_or(json!({}));
|
|
let form = args
|
|
.get("form")
|
|
.cloned()
|
|
.ok_or_else(|| "missing `form`".to_string())?;
|
|
let id = arg_str(args, "id")?.to_string();
|
|
compose::compose_form(&page, &form, &id)
|
|
});
|
|
|
|
web_ffi!(web_render, |args: &Value| {
|
|
let page = args.get("page").cloned().unwrap_or_else(|| args.clone());
|
|
let db_url = db_url_of(args).ok();
|
|
let html = render::render_page(&page, db_url.as_deref());
|
|
Ok(Value::String(html))
|
|
});
|
|
|
|
web_ffi!(web_db_new, |args: &Value| {
|
|
let url = arg_str_opt(args, "url").unwrap_or("sqlite:site.db");
|
|
Ok(json!({ "url": url }))
|
|
});
|
|
|
|
web_ffi!(web_db_init, |args: &Value| {
|
|
let url = db_url_of(args)?;
|
|
let name = arg_str(args, "name")
|
|
.or_else(|_| arg_str(args, "table"))?
|
|
.to_string();
|
|
let fields = args.get("fields").cloned().unwrap_or(json!([]));
|
|
db::init(&url, &name, &fields)
|
|
});
|
|
|
|
web_ffi!(web_db_insert, |args: &Value| {
|
|
let url = db_url_of(args)?;
|
|
let table = arg_str(args, "table")?.to_string();
|
|
let rows = args
|
|
.get("rows")
|
|
.or_else(|| args.get("row"))
|
|
.cloned()
|
|
.unwrap_or(json!([]));
|
|
db::insert(&url, &table, &rows)
|
|
});
|
|
|
|
web_ffi!(web_db_select, |args: &Value| {
|
|
let url = db_url_of(args)?;
|
|
let table = arg_str(args, "table")?.to_string();
|
|
let limit = args
|
|
.get("limit")
|
|
.and_then(|v| v.as_i64())
|
|
.unwrap_or(200);
|
|
let where_v = match args.get("where") {
|
|
None | Some(Value::Null) => None,
|
|
Some(Value::String(s))
|
|
if s.is_empty()
|
|
|| s.eq_ignore_ascii_case("none")
|
|
|| s.eq_ignore_ascii_case("null") =>
|
|
{
|
|
None
|
|
}
|
|
Some(v) => Some(v),
|
|
};
|
|
db::select(&url, &table, limit, where_v)
|
|
});
|
|
|
|
web_ffi!(web_db_get, |args: &Value| {
|
|
let url = db_url_of(args)?;
|
|
let table = arg_str(args, "table")?.to_string();
|
|
let id = arg_text(args, "id")?;
|
|
db::get(&url, &table, &id)
|
|
});
|
|
|
|
web_ffi!(web_db_update, |args: &Value| {
|
|
let url = db_url_of(args)?;
|
|
let table = arg_str(args, "table")?.to_string();
|
|
let id = arg_text(args, "id")?;
|
|
let row = args.get("row").cloned().unwrap_or(json!({}));
|
|
db::update(&url, &table, &id, &row)
|
|
});
|
|
|
|
web_ffi!(web_db_delete, |args: &Value| {
|
|
let url = db_url_of(args)?;
|
|
let table = arg_str(args, "table")?.to_string();
|
|
let id = arg_text(args, "id")?;
|
|
db::delete(&url, &table, &id)
|
|
});
|
|
|
|
web_ffi!(web_db_exec, |args: &Value| {
|
|
let url = db_url_of(args)?;
|
|
let sql = arg_str(args, "sql")?.to_string();
|
|
let args_v = args.get("args");
|
|
db::exec(&url, &sql, args_v)
|
|
});
|
|
|
|
web_ffi!(web_db_list_tables, |args: &Value| {
|
|
let url = db_url_of(args)?;
|
|
let tables = db::list_tables(&url)?;
|
|
Ok(json!({ "tables": tables }))
|
|
});
|
|
|
|
web_ffi!(web_app_new, |args: &Value| {
|
|
let page = args.get("page").cloned().unwrap_or(json!({}));
|
|
let db = args.get("db").cloned().unwrap_or(Value::Null);
|
|
let host = arg_str_opt(args, "host").unwrap_or("127.0.0.1");
|
|
let port = args
|
|
.get("port")
|
|
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
|
.unwrap_or(18081);
|
|
let admin = match args.get("admin") {
|
|
Some(Value::Bool(b)) => *b,
|
|
Some(Value::String(s)) => matches!(s.as_str(), "true" | "True" | "1" | "yes"),
|
|
Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0,
|
|
_ => false,
|
|
};
|
|
Ok(json!({
|
|
"page": page,
|
|
"db": db,
|
|
"host": host,
|
|
"port": port,
|
|
"admin": admin,
|
|
"forms": {},
|
|
"routes": {},
|
|
"ws_routes": {},
|
|
"static_dir": null,
|
|
"static_mount": "/static",
|
|
}))
|
|
});
|
|
|
|
fn normalize_route_path(raw: &str) -> Result<String, String> {
|
|
let s = raw.trim();
|
|
if s.is_empty() {
|
|
return Err("route path is empty".into());
|
|
}
|
|
if s == "/" {
|
|
return Err("route path `/` is reserved for the home page".into());
|
|
}
|
|
let mut path = if s.starts_with('/') {
|
|
s.to_string()
|
|
} else {
|
|
format!("/{s}")
|
|
};
|
|
while path.len() > 1 && path.ends_with('/') {
|
|
path.pop();
|
|
}
|
|
// reserved prefixes
|
|
if path == "/admin"
|
|
|| path.starts_with("/admin/")
|
|
|| path == "/_form"
|
|
|| path.starts_with("/_form/")
|
|
|| path == "/_part"
|
|
|| path.starts_with("/_part/")
|
|
|| path == "/static"
|
|
|| path.starts_with("/static/")
|
|
{
|
|
return Err(format!("route path `{path}` is reserved"));
|
|
}
|
|
Ok(path)
|
|
}
|
|
|
|
web_ffi!(web_app_route, |args: &Value| {
|
|
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
|
let path = normalize_route_path(arg_str(args, "path")?)?;
|
|
let mut page = args
|
|
.get("page")
|
|
.cloned()
|
|
.ok_or_else(|| "missing `page` for route".to_string())?;
|
|
// Stamp mount path so render can emit `{path}/_part/{id}` slot sources.
|
|
if let Some(obj) = page.as_object_mut() {
|
|
obj.insert("_route".into(), json!(&path));
|
|
}
|
|
let obj = app
|
|
.as_object_mut()
|
|
.ok_or_else(|| "app must be a map".to_string())?;
|
|
let routes = obj
|
|
.entry("routes".to_string())
|
|
.or_insert_with(|| json!({}));
|
|
let rmap = routes
|
|
.as_object_mut()
|
|
.ok_or_else(|| "app.routes must be a map".to_string())?;
|
|
rmap.insert(path, page);
|
|
Ok(app)
|
|
});
|
|
|
|
web_ffi!(web_app_route_ws, |args: &Value| {
|
|
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
|
let path = normalize_route_path(arg_str(args, "path")?)?;
|
|
let echo = match args.get("echo") {
|
|
None | Some(Value::Null) => true,
|
|
Some(Value::Bool(b)) => *b,
|
|
Some(Value::String(s)) => matches!(s.as_str(), "true" | "True" | "1" | "yes"),
|
|
Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0,
|
|
Some(_) => true,
|
|
};
|
|
let obj = app
|
|
.as_object_mut()
|
|
.ok_or_else(|| "app must be a map".to_string())?;
|
|
let ws_routes = obj
|
|
.entry("ws_routes".to_string())
|
|
.or_insert_with(|| json!({}));
|
|
let wmap = ws_routes
|
|
.as_object_mut()
|
|
.ok_or_else(|| "app.ws_routes must be a map".to_string())?;
|
|
wmap.insert(path, json!(echo));
|
|
Ok(app)
|
|
});
|
|
|
|
web_ffi!(web_ws_connect, |args: &Value| {
|
|
let url = arg_str(args, "url")?.to_string();
|
|
let message = arg_str_opt(args, "message").unwrap_or("");
|
|
let headers = args.get("headers");
|
|
let timeout_sec = args
|
|
.get("timeout_sec")
|
|
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
|
.unwrap_or(30);
|
|
match crate::ws::connect(&url, message, headers, timeout_sec) {
|
|
Ok(v) => Ok(v),
|
|
Err(e) => Ok(json!({ "ok": false, "error": e })),
|
|
}
|
|
});
|
|
|
|
web_ffi!(web_session_new, |args: &Value| {
|
|
session::abi_session_new(args)
|
|
});
|
|
|
|
web_ffi!(web_session_set, |args: &Value| {
|
|
session::abi_session_set(args)
|
|
});
|
|
|
|
web_ffi!(web_session_get, |args: &Value| {
|
|
session::abi_session_get(args)
|
|
});
|
|
|
|
web_ffi!(web_session_del, |args: &Value| {
|
|
session::abi_session_del(args)
|
|
});
|
|
|
|
web_ffi!(web_session_destroy, |args: &Value| {
|
|
session::abi_session_destroy(args)
|
|
});
|
|
|
|
web_ffi!(web_auth_login, |args: &Value| {
|
|
session::abi_auth_login(args)
|
|
});
|
|
|
|
web_ffi!(web_auth_check, |args: &Value| {
|
|
session::abi_auth_check(args)
|
|
});
|
|
|
|
web_ffi!(web_auth_logout, |args: &Value| {
|
|
session::abi_auth_logout(args)
|
|
});
|
|
|
|
web_ffi!(web_auth_new, |args: &Value| {
|
|
let users = args.get("users").cloned().unwrap_or(Value::Null);
|
|
let session_ttl = args
|
|
.get("session_ttl")
|
|
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
|
.unwrap_or(3600);
|
|
Ok(json!({ "users": users, "session_ttl": session_ttl }))
|
|
});
|
|
|
|
web_ffi!(web_app_auth, |args: &Value| {
|
|
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
|
let users = args.get("users").cloned().unwrap_or(Value::Null);
|
|
let session_ttl = args
|
|
.get("session_ttl")
|
|
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
|
.unwrap_or(3600);
|
|
let obj = app
|
|
.as_object_mut()
|
|
.ok_or_else(|| "app must be a map".to_string())?;
|
|
obj.insert(
|
|
"auth".to_string(),
|
|
json!({ "users": users, "session_ttl": session_ttl }),
|
|
);
|
|
Ok(app)
|
|
});
|
|
|
|
web_ffi!(web_app_mount_form, |args: &Value| {
|
|
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
|
let id = arg_str(args, "id")?.to_string();
|
|
let form_v = args
|
|
.get("form")
|
|
.cloned()
|
|
.ok_or_else(|| "missing `form`".to_string())?;
|
|
let obj = app.as_object_mut().ok_or_else(|| "app must be a map".to_string())?;
|
|
let forms = obj
|
|
.entry("forms".to_string())
|
|
.or_insert_with(|| json!({}));
|
|
let fmap = forms
|
|
.as_object_mut()
|
|
.ok_or_else(|| "app.forms must be a map".to_string())?;
|
|
fmap.insert(id, form_v);
|
|
Ok(app)
|
|
});
|
|
|
|
web_ffi!(web_app_static, |args: &Value| {
|
|
let mut app = args.get("app").cloned().unwrap_or(json!({}));
|
|
let dir = arg_str(args, "dir")?.to_string();
|
|
if dir.trim().is_empty() {
|
|
return Err("static `dir` is empty".into());
|
|
}
|
|
let mount = arg_str_opt(args, "mount").unwrap_or("/static");
|
|
let mount = http::normalize_static_mount(mount);
|
|
// Also reserve custom mounts against later routes.
|
|
if mount == "/admin"
|
|
|| mount.starts_with("/admin/")
|
|
|| mount == "/_form"
|
|
|| mount.starts_with("/_form/")
|
|
|| mount == "/_part"
|
|
|| mount.starts_with("/_part/")
|
|
{
|
|
return Err(format!("static mount `{mount}` is reserved"));
|
|
}
|
|
let obj = app
|
|
.as_object_mut()
|
|
.ok_or_else(|| "app must be a map".to_string())?;
|
|
obj.insert("static_dir".into(), json!(dir));
|
|
obj.insert("static_mount".into(), json!(mount));
|
|
Ok(app)
|
|
});
|
|
|
|
web_ffi!(web_form_new, |args: &Value| {
|
|
let table = arg_str_opt(args, "table");
|
|
let action = arg_str_opt(args, "action").unwrap_or("insert");
|
|
let id = arg_str_opt(args, "id");
|
|
Ok(form::form_new(table, action, id))
|
|
});
|
|
|
|
web_ffi!(web_form_fields, |args: &Value| {
|
|
let form_v = args.get("form").cloned().unwrap_or(json!({}));
|
|
let fields = args
|
|
.get("fields")
|
|
.cloned()
|
|
.ok_or_else(|| "missing `fields`".to_string())?;
|
|
Ok(form::set_fields(&form_v, &fields))
|
|
});
|
|
|
|
web_ffi!(web_form_rules, |args: &Value| {
|
|
let form_v = args.get("form").cloned().unwrap_or(json!({}));
|
|
let rules = args
|
|
.get("rules")
|
|
.cloned()
|
|
.ok_or_else(|| "missing `rules`".to_string())?;
|
|
Ok(form::set_rules(&form_v, &rules))
|
|
});
|
|
|
|
web_ffi!(web_form_validate, |args: &Value| {
|
|
let form_v = args.get("form").cloned().unwrap_or(json!({}));
|
|
let data = args
|
|
.get("data")
|
|
.cloned()
|
|
.ok_or_else(|| "missing `data`".to_string())?;
|
|
let rules = args.get("rules");
|
|
Ok(form::validate(&form_v, rules, &data))
|
|
});
|
|
|
|
web_ffi!(web_form_render, |args: &Value| {
|
|
let form_v = args.get("form").cloned().unwrap_or(json!({}));
|
|
let id = arg_str_opt(args, "id").unwrap_or("form");
|
|
let data = args.get("data");
|
|
let errors = args.get("errors");
|
|
Ok(Value::String(form::render(
|
|
&form_v,
|
|
id,
|
|
data,
|
|
errors,
|
|
)))
|
|
});
|
|
|
|
web_ffi!(web_form_submit, |args: &Value| {
|
|
let form_v = args.get("form").cloned().unwrap_or(json!({}));
|
|
let data = args
|
|
.get("data")
|
|
.cloned()
|
|
.ok_or_else(|| "missing `data`".to_string())?;
|
|
let url = db_url_of(args)?;
|
|
form::submit(&form_v, &data, &url)
|
|
});
|
|
|
|
web_ffi!(web_form_from_schema, |args: &Value| {
|
|
let url = db_url_of(args)?;
|
|
let table = arg_str(args, "table")?.to_string();
|
|
let action = arg_str_opt(args, "action").unwrap_or("insert");
|
|
let id = match args.get("id") {
|
|
None | Some(Value::Null) => None,
|
|
Some(_) => Some(arg_text(args, "id")?),
|
|
};
|
|
form::from_schema(&url, &table, action, id.as_deref())
|
|
});
|
|
|
|
web_ffi!(web_db_table_info, |args: &Value| {
|
|
let url = db_url_of(args)?;
|
|
let table = arg_str(args, "table")?.to_string();
|
|
let cols = db::table_info(&url, &table)?;
|
|
let arr: Vec<Value> = cols
|
|
.into_iter()
|
|
.map(|c| {
|
|
json!({
|
|
"name": c.name,
|
|
"type": c.sql_type,
|
|
"notnull": c.notnull,
|
|
"pk": c.pk,
|
|
})
|
|
})
|
|
.collect();
|
|
Ok(json!({ "columns": arr }))
|
|
});
|
|
|
|
web_ffi!(web_listen, |args: &Value| {
|
|
use std::collections::HashMap;
|
|
use std::path::PathBuf;
|
|
let (
|
|
page,
|
|
db_url,
|
|
host,
|
|
port,
|
|
admin,
|
|
forms,
|
|
routes,
|
|
static_dir,
|
|
static_mount,
|
|
auth_users,
|
|
session_ttl,
|
|
ws_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();
|
|
let host = arg_str_opt(args, "host").unwrap_or("127.0.0.1");
|
|
let port = args
|
|
.get("port")
|
|
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
|
.unwrap_or(18081) as u16;
|
|
let admin = match args.get("admin") {
|
|
Some(Value::Bool(b)) => *b,
|
|
_ => false,
|
|
};
|
|
let static_dir = arg_str_opt(args, "static_dir").map(PathBuf::from);
|
|
let static_mount = arg_str_opt(args, "static_mount")
|
|
.unwrap_or("/static")
|
|
.to_string();
|
|
let auth_users = args
|
|
.get("auth")
|
|
.or_else(|| args.get("users"))
|
|
.cloned()
|
|
.filter(|v| !matches!(v, Value::Null));
|
|
let session_ttl = args
|
|
.get("session_ttl")
|
|
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
|
.unwrap_or(3600);
|
|
(
|
|
page,
|
|
db_url,
|
|
host.to_string(),
|
|
port,
|
|
admin,
|
|
HashMap::new(),
|
|
HashMap::new(),
|
|
static_dir,
|
|
static_mount,
|
|
auth_users,
|
|
session_ttl,
|
|
HashMap::new(),
|
|
)
|
|
} else {
|
|
let app = args.get("app").cloned().unwrap_or_else(|| args.clone());
|
|
let page = app.get("page").cloned().unwrap_or(json!({}));
|
|
let db_url = app
|
|
.get("db")
|
|
.and_then(|d| d.get("url"))
|
|
.and_then(|v| v.as_str())
|
|
.map(|s| s.to_string())
|
|
.or_else(|| arg_str_opt(&app, "db_url").map(|s| s.to_string()))
|
|
.map(|s| resolve_db_url(&s));
|
|
let host = app
|
|
.get("host")
|
|
.and_then(|v| v.as_str())
|
|
.unwrap_or("127.0.0.1")
|
|
.to_string();
|
|
let port = app
|
|
.get("port")
|
|
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
|
.unwrap_or(18081) as u16;
|
|
let admin = app
|
|
.get("admin")
|
|
.and_then(|v| v.as_bool())
|
|
.unwrap_or(false);
|
|
let mut forms = HashMap::new();
|
|
if let Some(obj) = app.get("forms").and_then(|v| v.as_object()) {
|
|
for (k, v) in obj {
|
|
forms.insert(k.clone(), v.clone());
|
|
}
|
|
}
|
|
let mut routes = HashMap::new();
|
|
if let Some(obj) = app.get("routes").and_then(|v| v.as_object()) {
|
|
for (k, v) in obj {
|
|
routes.insert(k.clone(), v.clone());
|
|
}
|
|
}
|
|
let mut ws_routes = HashMap::new();
|
|
if let Some(obj) = app.get("ws_routes").and_then(|v| v.as_object()) {
|
|
for (k, v) in obj {
|
|
let echo = match v {
|
|
Value::Bool(b) => *b,
|
|
Value::String(s) => matches!(s.as_str(), "true" | "True" | "1" | "yes"),
|
|
_ => true,
|
|
};
|
|
ws_routes.insert(k.clone(), echo);
|
|
}
|
|
}
|
|
let static_dir = app
|
|
.get("static_dir")
|
|
.and_then(|v| v.as_str())
|
|
.filter(|s| !s.is_empty())
|
|
.map(PathBuf::from);
|
|
let static_mount = app
|
|
.get("static_mount")
|
|
.and_then(|v| v.as_str())
|
|
.unwrap_or("/static")
|
|
.to_string();
|
|
// `auth` may hold the users table directly or `{users:…, ttl:…}`.
|
|
let (auth_users, session_ttl) = match app.get("auth") {
|
|
Some(Value::Object(m)) if m.contains_key("users") => (
|
|
m.get("users").cloned(),
|
|
m.get("ttl")
|
|
.or_else(|| m.get("session_ttl"))
|
|
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
|
.unwrap_or(3600),
|
|
),
|
|
Some(other) if !matches!(other, Value::Null) => (
|
|
Some(other.clone()),
|
|
app.get("session_ttl")
|
|
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
|
.unwrap_or(3600),
|
|
),
|
|
_ => (
|
|
None,
|
|
app.get("session_ttl")
|
|
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
|
|
.unwrap_or(3600),
|
|
),
|
|
};
|
|
(
|
|
page,
|
|
db_url,
|
|
host,
|
|
port,
|
|
admin,
|
|
forms,
|
|
routes,
|
|
static_dir,
|
|
static_mount,
|
|
auth_users,
|
|
session_ttl,
|
|
ws_routes,
|
|
)
|
|
};
|
|
let static_dir = static_dir.map(|p| {
|
|
if p.is_absolute() {
|
|
p
|
|
} else {
|
|
entry_dir().join(p)
|
|
}
|
|
});
|
|
http::listen(
|
|
&page,
|
|
db_url.as_deref(),
|
|
&host,
|
|
port,
|
|
admin,
|
|
forms,
|
|
routes,
|
|
static_dir,
|
|
&static_mount,
|
|
auth_users,
|
|
session_ttl,
|
|
ws_routes,
|
|
)
|
|
});
|
|
|
|
fn register(host: &MarqdoHostApi, name: &str, params: &str, fn_ptr: PluginFn) -> c_int {
|
|
let register = match host.register_fn {
|
|
Some(f) => f,
|
|
None => return 1,
|
|
};
|
|
let n = CString::new(name).unwrap();
|
|
let p = CString::new(params).unwrap();
|
|
unsafe { register(host.userdata, n.as_ptr(), p.as_ptr(), fn_ptr) }
|
|
}
|
|
|
|
#[no_mangle]
|
|
pub unsafe extern "C" fn marqdo_plugin_abi_version() -> u32 {
|
|
ABI_VERSION
|
|
}
|
|
|
|
#[no_mangle]
|
|
pub unsafe extern "C" fn marqdo_plugin_shutdown() {}
|
|
|
|
#[no_mangle]
|
|
pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int {
|
|
if host.is_null() {
|
|
return 1;
|
|
}
|
|
let host = &*host;
|
|
HOST_ALLOC = host.alloc;
|
|
HOST_FREE = host.free;
|
|
HOST_QUERY = host.host_query;
|
|
HOST_USERDATA = host.userdata;
|
|
if host.host_query.is_none() {
|
|
return 1;
|
|
}
|
|
|
|
let regs = [
|
|
("web_page_new", "title,intro", web_page_new as PluginFn),
|
|
(
|
|
"web_compose_components",
|
|
"page,components",
|
|
web_compose_components as PluginFn,
|
|
),
|
|
("web_compose_main", "page,main", web_compose_main as PluginFn),
|
|
(
|
|
"web_compose_form",
|
|
"page,form,id",
|
|
web_compose_form as PluginFn,
|
|
),
|
|
("web_render", "page", web_render as PluginFn),
|
|
("web_db_new", "url", web_db_new as PluginFn),
|
|
("web_db_init", "url,name,fields", web_db_init as PluginFn),
|
|
("web_db_insert", "url,table,rows", web_db_insert as PluginFn),
|
|
(
|
|
"web_db_select",
|
|
"url,table,where,limit",
|
|
web_db_select as PluginFn,
|
|
),
|
|
("web_db_get", "url,table,id", web_db_get as PluginFn),
|
|
("web_db_update", "url,table,id,row", web_db_update as PluginFn),
|
|
("web_db_delete", "url,table,id", web_db_delete as PluginFn),
|
|
("web_db_exec", "url,sql,args", web_db_exec as PluginFn),
|
|
("web_db_list_tables", "url", web_db_list_tables as PluginFn),
|
|
(
|
|
"web_app_new",
|
|
"page,db,admin,host,port",
|
|
web_app_new as PluginFn,
|
|
),
|
|
("web_app_route", "app,path,page", web_app_route as PluginFn),
|
|
(
|
|
"web_app_mount_form",
|
|
"app,id,form",
|
|
web_app_mount_form as PluginFn,
|
|
),
|
|
(
|
|
"web_app_static",
|
|
"app,dir,mount",
|
|
web_app_static as PluginFn,
|
|
),
|
|
("web_form_new", "table,action,id", web_form_new as PluginFn),
|
|
("web_form_fields", "form,fields", web_form_fields as PluginFn),
|
|
("web_form_rules", "form,rules", web_form_rules as PluginFn),
|
|
(
|
|
"web_form_validate",
|
|
"form,rules,data",
|
|
web_form_validate as PluginFn,
|
|
),
|
|
("web_form_render", "form,id", web_form_render as PluginFn),
|
|
("web_form_submit", "form,data,url", web_form_submit as PluginFn),
|
|
(
|
|
"web_form_from_schema",
|
|
"url,table,action",
|
|
web_form_from_schema as PluginFn,
|
|
),
|
|
("web_db_table_info", "url,table", web_db_table_info as PluginFn),
|
|
("web_session_new", "ttl_sec", web_session_new as PluginFn),
|
|
("web_session_set", "id,key,value", web_session_set as PluginFn),
|
|
("web_session_get", "id,key", web_session_get as PluginFn),
|
|
("web_session_del", "id,key", web_session_del as PluginFn),
|
|
("web_session_destroy", "id", web_session_destroy as PluginFn),
|
|
(
|
|
"web_auth_login",
|
|
"username,password,users,session_ttl",
|
|
web_auth_login as PluginFn,
|
|
),
|
|
("web_auth_check", "session_id", web_auth_check as PluginFn),
|
|
("web_auth_logout", "session_id", web_auth_logout as PluginFn),
|
|
("web_auth_new", "users,session_ttl", web_auth_new as PluginFn),
|
|
("web_app_auth", "app,users,session_ttl", web_app_auth as PluginFn),
|
|
(
|
|
"web_app_route_ws",
|
|
"app,path,echo",
|
|
web_app_route_ws as PluginFn,
|
|
),
|
|
(
|
|
"web_ws_connect",
|
|
"url,message,headers,timeout_sec",
|
|
web_ws_connect as PluginFn,
|
|
),
|
|
("web_listen", "app", web_listen as PluginFn),
|
|
];
|
|
for (name, params, f) in regs {
|
|
if register(host, name, params, f) != 0 {
|
|
return 1;
|
|
}
|
|
}
|
|
0
|
|
}
|