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' 'wasm-unsafe-eval'; worker-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, 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> { 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::>(); match s.selected(&ids) { Err(AppError::NotFound(_)) => Err("选择的档案已不存在,请刷新记录".into()), other => other, } } async fn handle(State(worker): State, 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::>::try_from_uri( req.uri(), ) { Ok(q) => q.0, Err(_) => return error("查询参数无效".into()), }; let body = if method == "POST" || method == "PATCH" || method == "PUT" { 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::(&b) { Ok(v) => v, Err(_) => return error("提交内容不是有效 JSON".into()), } } } Err(_) => return error("提交内容过大,单张照片最多 5 MB".into()), } } else { Value::Null }; if method == "GET" && let Some((bytes, mime)) = crate::web_assets::resource(&path) { return binary(bytes.to_vec(), mime, None, None); } let result=worker.run(move|s|{ if method=="GET"&&path=="/api/monitoring/events"{return Ok(json_response(StatusCode::OK,crate::geofences::events(&s.db,¶ms)?));} if method=="GET"&&path=="/api/geofences"{return Ok(json_response(StatusCode::OK,serde_json::to_value(crate::geofences::load(&s.db)?).map_err(|e|AppError::Internal(e.to_string()))?));} if let Some(id)=path.strip_prefix("/api/geofences/") { let snapshot=if method=="PUT"{ let mutation=serde_json::from_value(body).map_err(|_|AppError::Validation("围栏参数无效".into()))?; crate::geofences::save(&mut s.db,id,mutation)? }else if method=="DELETE"{ let expected=params.get("revision").and_then(|v|v.parse::().ok()).ok_or(AppError::Validation("请提供有效的围栏版本".into()))?; crate::geofences::remove(&mut s.db,id,expected)? }else{return Err(AppError::NotFound("围栏接口不存在"))}; return Ok(json_response(StatusCode::OK,serde_json::to_value(snapshot).map_err(|e|AppError::Internal(e.to_string()))?)); } if method=="GET"&&path=="/api/target-lists"{ if let Some(known)=params.get("revision") { let known=known.parse::().map_err(|_|AppError::Validation("名单版本无效".into()))?; if crate::target_lists::revision(&s.db)?==known{return Ok(StatusCode::NOT_MODIFIED.into_response())} } return Ok(json_response(StatusCode::OK,serde_json::to_value(crate::target_lists::load(&s.db)?).map_err(|e|AppError::Internal(e.to_string()))?)); } if let Some(id)=path.strip_prefix("/api/target-lists/") { let snapshot=if method=="PUT"{ let mutation=serde_json::from_value(body).map_err(|_|AppError::Validation("名单类型、备注或版本无效".into()))?; crate::target_lists::save(&mut s.db,id,mutation)? }else if method=="DELETE"{ let expected=params.get("revision").and_then(|v|v.parse::().ok()).ok_or(AppError::Validation("请提供有效的名单版本".into()))?; crate::target_lists::remove(&mut s.db,id,expected)? }else{return Err(AppError::NotFound("名单接口不存在"))}; return Ok(json_response(StatusCode::OK,serde_json::to_value(snapshot).map_err(|e|AppError::Internal(e.to_string()))?)); } if path=="/api/appearance" && (method=="GET" || method=="PATCH") { let value=if method=="GET" { crate::appearance::load(&s.db)? } else { crate::appearance::save(&mut s.db,body)? }; return Ok(json_response(StatusCode::OK,serde_json::to_value(value).map_err(|e|AppError::Internal(e.to_string()))?)); } 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{params.get(key).map(|s|s.parse::().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::>()})};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::>(); 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::().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'")))} Ok(json_response(StatusCode::NOT_FOUND,json!({"error":"页面不存在"}))) }).await; match result { Ok(response) => response, Err(e) => error(e), } }