```
feat(registry): 迁移至 Rust + Axum + SQLite 并新增编辑、分页和档案同步功能 - 后端从 Node.js 迁移到 Rust,使用 Axum 框架和 SQLite 存储 - 新增档案编辑对话框,支持修改机型、登记人及替换/删除照片 - 档案列表增加分页导航(每页20条) - 新增档案同步状态提示及手动重试同步按钮 - Node.js 原版后端及网页保留为回退方案,移至 legacy-web 目录 - 更新 .gitignore 添加 Rust 构建产物(target、dist) - 更新 README 文档,补充 Rust 启动、开发、检查及打包说明 - 启动源码版.cmd 默认转发至 Rust 版启动脚本 ```
This commit is contained in:
+170
@@ -0,0 +1,170 @@
|
||||
use crate::error::{AppError, Result};
|
||||
use crate::{
|
||||
Worker, archive,
|
||||
store::{Store, valid_id},
|
||||
};
|
||||
use axum::{
|
||||
Router,
|
||||
body::Body,
|
||||
extract::{DefaultBodyLimit, Request, State},
|
||||
http::{HeaderValue, StatusCode},
|
||||
middleware::{self, Next},
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub fn router(worker: Worker) -> Router {
|
||||
Router::new()
|
||||
.fallback(handle)
|
||||
.layer(DefaultBodyLimit::max(16 * 1024 * 1024))
|
||||
.layer(middleware::from_fn(headers))
|
||||
.with_state(worker)
|
||||
}
|
||||
async fn headers(req: Request, next: Next) -> Response {
|
||||
let mut r = next.run(req).await;
|
||||
for (key, value) in [
|
||||
("cache-control", "no-store"),
|
||||
("x-content-type-options", "nosniff"),
|
||||
("access-control-allow-origin", "*"),
|
||||
(
|
||||
"access-control-allow-methods",
|
||||
"GET, POST, PATCH, DELETE, OPTIONS",
|
||||
),
|
||||
("access-control-allow-headers", "content-type"),
|
||||
("access-control-allow-private-network", "true"),
|
||||
] {
|
||||
r.headers_mut().insert(key, HeaderValue::from_static(value));
|
||||
}
|
||||
if !r.headers().contains_key("content-security-policy") {
|
||||
r.headers_mut().insert("content-security-policy",HeaderValue::from_static("default-src 'self'; img-src 'self' data: blob:; style-src 'self'; script-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'"));
|
||||
}
|
||||
r
|
||||
}
|
||||
fn json_response(status: StatusCode, v: Value) -> Response {
|
||||
(status, axum::Json(v)).into_response()
|
||||
}
|
||||
fn error(e: AppError) -> Response {
|
||||
let (status, message) = match e {
|
||||
AppError::Validation(s) => (StatusCode::BAD_REQUEST, s),
|
||||
AppError::NotFound(s) => (StatusCode::NOT_FOUND, s.to_owned()),
|
||||
AppError::Internal(s) => {
|
||||
eprintln!("内部错误:{s}");
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
"服务内部错误,请检查日志后重试".to_owned(),
|
||||
)
|
||||
}
|
||||
};
|
||||
json_response(status, json!({"error":message}))
|
||||
}
|
||||
fn binary(data: Vec<u8>, kind: &str, filename: Option<&str>, csp: Option<&str>) -> Response {
|
||||
let mut r = Response::new(Body::from(data));
|
||||
r.headers_mut()
|
||||
.insert("content-type", HeaderValue::from_str(kind).unwrap());
|
||||
if let Some(name) = filename
|
||||
&& let Ok(h) = HeaderValue::from_str(&format!("attachment; filename=\"{name}\""))
|
||||
{
|
||||
r.headers_mut().insert("content-disposition", h);
|
||||
}
|
||||
if let Some(csp) = csp {
|
||||
r.headers_mut().insert(
|
||||
"content-security-policy",
|
||||
HeaderValue::from_str(csp).unwrap(),
|
||||
);
|
||||
}
|
||||
r
|
||||
}
|
||||
fn selected(s: &Store, v: &Value) -> Result<Vec<Value>> {
|
||||
let ids = v["ids"].as_array().ok_or("请先勾选要导出的档案")?;
|
||||
if ids.is_empty() || ids.len() > 5000 {
|
||||
return Err("请先勾选要导出的档案".into());
|
||||
}
|
||||
let mut wanted = std::collections::HashSet::new();
|
||||
for id in ids {
|
||||
let id = id.as_str().filter(|s| valid_id(s)).ok_or("档案 ID 无效")?;
|
||||
wanted.insert(id);
|
||||
}
|
||||
let ids = wanted.into_iter().map(str::to_owned).collect::<Vec<_>>();
|
||||
match s.selected(&ids) {
|
||||
Err(AppError::NotFound(_)) => Err("选择的档案已不存在,请刷新记录".into()),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
async fn handle(State(worker): State<Worker>, req: Request) -> Response {
|
||||
let method = req.method().to_string();
|
||||
let path = req.uri().path().to_owned();
|
||||
let origin = req.headers().get("origin").and_then(|h| h.to_str().ok());
|
||||
if origin.is_some_and(|o| o != "http://127.0.0.1:8787" && o != "http://localhost:8787")
|
||||
&& path != "/api/resolve"
|
||||
{
|
||||
return json_response(
|
||||
StatusCode::FORBIDDEN,
|
||||
json!({"error":"只允许从本地登记站访问"}),
|
||||
);
|
||||
}
|
||||
if method == "OPTIONS" {
|
||||
return StatusCode::NO_CONTENT.into_response();
|
||||
}
|
||||
let params =
|
||||
match axum::extract::Query::<std::collections::HashMap<String, String>>::try_from_uri(
|
||||
req.uri(),
|
||||
) {
|
||||
Ok(q) => q.0,
|
||||
Err(_) => return error("查询参数无效".into()),
|
||||
};
|
||||
let body = if method == "POST" || method == "PATCH" {
|
||||
match axum::body::to_bytes(req.into_body(), 16 * 1024 * 1024).await {
|
||||
Ok(b) => {
|
||||
if path == "/api/archive/retry" && b.is_empty() {
|
||||
json!({})
|
||||
} else {
|
||||
match serde_json::from_slice::<Value>(&b) {
|
||||
Ok(v) => v,
|
||||
Err(_) => return error("提交内容不是有效 JSON".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => return error("提交内容过大,单张照片最多 5 MB".into()),
|
||||
}
|
||||
} else {
|
||||
Value::Null
|
||||
};
|
||||
let result=worker.run(move|s|{
|
||||
if method=="GET"&&path=="/api/archive/status"{return Ok(json_response(StatusCode::OK,if s.pending()?.is_some(){json!({"archiveStatus":"pending","warning":"档案或备份待同步,请重试。"})}else{json!({"archiveStatus":"synced"})}));}
|
||||
if method=="GET"&&path=="/api/records"{
|
||||
let q=params.get("q").map(|s|s.trim()).unwrap_or("");
|
||||
let paged=params.contains_key("page")||params.contains_key("pageSize");
|
||||
let value=if paged{let parse=|key:&str,default:usize|->Result<usize>{params.get(key).map(|s|s.parse::<usize>().map_err(|_|"分页参数无效".into())).unwrap_or(Ok(default))};s.page(q,parse("page",1)?,parse("pageSize",20)?)?}else{json!({"records":s.list(q)?.into_iter().map(archive::public).collect::<Vec<_>>()})};return Ok(json_response(StatusCode::OK,value));
|
||||
}
|
||||
if method=="POST"&&path=="/api/records"{let mut v=s.register(body)?;v["record"]=archive::public(v["record"].take());return Ok(json_response(StatusCode::OK,archive::finish(s,v)))}
|
||||
if method=="POST"&&path=="/api/archive/retry"{archive::sync(s).map_err(|e|format!("内部错误:档案同步失败:{e}"))?;return Ok(json_response(StatusCode::OK,json!({"archiveStatus":"synced"})))}
|
||||
if method=="POST"&&(path=="/api/export/archive"||path=="/api/export/excel"){
|
||||
let excel=path.ends_with("excel");let records=selected(s,&body)?;let bytes=archive::export(s,records,excel).map_err(|e|format!("内部错误:导出失败:{e}"))?;
|
||||
return Ok(binary(bytes,if excel{"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}else{"application/zip"},Some(if excel{"FPV-RID-records.xlsx"}else{"FPV-RID-archive.zip"}),None));
|
||||
}
|
||||
if method=="GET"&&path=="/api/resolve"{
|
||||
let uri:axum::http::Uri=params.get("url").ok_or("二维码内容不是有效网址")?.parse().map_err(|_|"二维码内容不是有效网址")?;
|
||||
if uri.scheme_str()!=Some("http")||!matches!(uri.host(),Some("127.0.0.1"|"localhost"))||uri.port_u16()!=Some(8787){return Err("二维码不是本机登记站生成的链接".into())}
|
||||
let id=uri.path().strip_prefix("/r/").filter(|id|valid_id(id)).ok_or("本地登记链接格式无效")?;
|
||||
return Ok(json_response(StatusCode::OK,archive::public(s.get(id)?)));
|
||||
}
|
||||
let parts=path.trim_start_matches('/').split('/').collect::<Vec<_>>();
|
||||
if parts.len()>=3&&parts[0]=="api"&&parts[1]=="records"&&valid_id(parts[2]){
|
||||
let id=parts[2];
|
||||
if parts.len()==3&&method=="PATCH"{let mut v=s.patch(id,body)?;v["record"]=archive::public(v["record"].take());return Ok(json_response(StatusCode::OK,archive::finish(s,v)))}
|
||||
if parts.len()==3&&method=="DELETE"{let v=s.delete(id,None)?;return Ok(json_response(StatusCode::OK,archive::finish(s,v)))}
|
||||
if parts.len()==5&&parts[3]=="photos"&&matches!(parts[4],"1"|"2"){
|
||||
let slot=parts[4].parse::<u8>().unwrap();if method=="DELETE"{let v=s.delete(id,Some(slot))?;return Ok(json_response(StatusCode::OK,archive::finish(s,v)))}
|
||||
if method=="GET"{let (mime,data)=s.photo(id,slot)?.ok_or(AppError::NotFound("照片不存在"))?;return Ok(binary(data,&mime,None,None))}
|
||||
}
|
||||
if parts.len()==4&&parts[3]=="archive"&&method=="GET"{let r=s.get(id)?;let name=format!("FPV-RID-{}.html",r["serialNo"].as_str().unwrap_or("record"));return Ok(binary(archive::card(s,&r,true)?.into_bytes(),"text/html; charset=utf-8",Some(&name),Some("default-src 'none'; img-src data:; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'")))}
|
||||
}
|
||||
if method=="GET"&&parts.len()==2&&parts[0]=="r"&&valid_id(parts[1]){return Ok(binary(archive::card(s,&s.get(parts[1])?,false)?.into_bytes(),"text/html; charset=utf-8",None,Some("default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'")))}
|
||||
if method=="GET"{let resource:Option<(&[u8],&str)>=match path.as_str(){"/"=>Some((include_bytes!("../registry/web/index.html"),"text/html; charset=utf-8")),"/app.js"=>Some((include_bytes!("../registry/web/app.js"),"text/javascript; charset=utf-8")),"/app.css"=>Some((include_bytes!("../registry/web/app.css"),"text/css; charset=utf-8")),"/vendor/qrcode.js"=>Some((include_bytes!("../registry/web/vendor/qrcode.js"),"text/javascript; charset=utf-8")),"/fpv-rid-icon.png"=>Some((include_bytes!("../registry/web/fpv-rid-icon.png"),"image/png")),_=>None};if let Some((bytes,mime))=resource{return Ok(binary(bytes.to_vec(),mime,None,None))}}
|
||||
Ok(json_response(StatusCode::NOT_FOUND,json!({"error":"页面不存在"})))
|
||||
}).await;
|
||||
match result {
|
||||
Ok(response) => response,
|
||||
Err(e) => error(e),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user