| 1 | use axum::extract::{Multipart, Path, Query, State}; |
| 2 | use axum::Json; |
| 3 | use serde::Deserialize; |
| 4 | use serde_json::json; |
| 5 | use sha2::{Digest, Sha256}; |
| 6 | use utopia_core::models::{Document, Role}; |
| 7 | use utopia_core::AppError; |
| 8 | use uuid::Uuid; |
| 9 | |
| 10 | use crate::auth::AuthUser; |
| 11 | use crate::error::ApiResult; |
| 12 | use crate::state::AppState; |
| 13 | |
| 14 | #[derive(Deserialize)] |
| 15 | pub struct UploadQuery { |
| 16 | /// 目标 folder 来源:上传直接归入该文件夹(仅 kind=folder 接受上传) |
| 17 | #[serde(default)] |
| 18 | pub source: Option<Uuid>, |
| 19 | } |
| 20 | |
| 21 | /// 批量上传(multipart,可多文件)。重复内容(同 KB 同 sha256)跳过。 |
| 22 | pub async fn upload( |
| 23 | State(state): State<AppState>, |
| 24 | AuthUser(user): AuthUser, |
| 25 | Path(kb_id): Path<Uuid>, |
| 26 | Query(q): Query<UploadQuery>, |
| 27 | mut multipart: Multipart, |
| 28 | ) -> ApiResult<Json<serde_json::Value>> { |
| 29 | utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Editor).await?; |
| 30 | let target_source = match q.source { |
| 31 | Some(sid) => { |
| 32 | let src = utopia_store::sources::get(&state.pool, sid).await?; |
| 33 | if src.kb_id != kb_id || src.kind != "folder" { |
| 34 | return Err(AppError::invalid( |
| 35 | "upload_needs_folder", |
| 36 | "Uploads can only target a folder source in this knowledge base", |
| 37 | ) |
| 38 | .into()); |
| 39 | } |
| 40 | Some(sid) |
| 41 | } |
| 42 | None => None, |
| 43 | }; |
| 44 | |
| 45 | let mut created: Vec<Document> = Vec::new(); |
| 46 | let mut skipped: Vec<serde_json::Value> = Vec::new(); |
| 47 | |
| 48 | while let Some(field) = multipart |
| 49 | .next_field() |
| 50 | .await |
| 51 | .map_err(|e| AppError::invalid_detail("bad_upload", "Malformed upload", e.to_string()))? |
| 52 | { |
| 53 | let Some(filename) = field.file_name().map(String::from) else { |
| 54 | continue; |
| 55 | }; |
| 56 | let mime = field |
| 57 | .content_type() |
| 58 | .unwrap_or("application/octet-stream") |
| 59 | .to_string(); |
| 60 | let bytes = field.bytes().await.map_err(|e| { |
| 61 | AppError::invalid_detail("upload_read_failed", "Failed to read upload", e.to_string()) |
| 62 | })?; |
| 63 | if bytes.is_empty() { |
| 64 | skipped.push(json!({ "filename": filename, "reason": "empty file" })); |
| 65 | continue; |
| 66 | } |
| 67 | |
| 68 | let sha256 = hex(&Sha256::digest(&bytes)); |
| 69 | state |
| 70 | .blob |
| 71 | .put(&sha256, &bytes) |
| 72 | .await |
| 73 | .map_err(AppError::Other)?; |
| 74 | |
| 75 | match utopia_store::documents::create( |
| 76 | &state.pool, |
| 77 | kb_id, |
| 78 | &filename, |
| 79 | &mime, |
| 80 | bytes.len() as i64, |
| 81 | &sha256, |
| 82 | target_source, |
| 83 | None, |
| 84 | None, |
| 85 | ) |
| 86 | .await |
| 87 | { |
| 88 | Ok(doc) => { |
| 89 | utopia_store::jobs::enqueue( |
| 90 | &state.pool, |
| 91 | "process_document", |
| 92 | json!({ "document_id": doc.id }), |
| 93 | ) |
| 94 | .await?; |
| 95 | created.push(doc); |
| 96 | } |
| 97 | Err(AppError::Conflict(_)) => { |
| 98 | skipped.push(json!({ "filename": filename, "reason": "duplicate content" })); |
| 99 | } |
| 100 | Err(e) => return Err(e.into()), |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | if created.is_empty() && skipped.is_empty() { |
| 105 | return Err(AppError::invalid("no_files", "No files received").into()); |
| 106 | } |
| 107 | Ok(Json(json!({ "created": created, "skipped": skipped }))) |
| 108 | } |
| 109 | |
| 110 | pub async fn list( |
| 111 | State(state): State<AppState>, |
| 112 | AuthUser(user): AuthUser, |
| 113 | Path(kb_id): Path<Uuid>, |
| 114 | ) -> ApiResult<Json<Vec<Document>>> { |
| 115 | utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?; |
| 116 | let docs = utopia_store::documents::list(&state.pool, kb_id).await?; |
| 117 | Ok(Json(docs)) |
| 118 | } |
| 119 | |
| 120 | /// 文档详情 + 全部分块(文档查看器用)。 |
| 121 | pub async fn detail( |
| 122 | State(state): State<AppState>, |
| 123 | AuthUser(user): AuthUser, |
| 124 | Path(id): Path<Uuid>, |
| 125 | ) -> ApiResult<Json<serde_json::Value>> { |
| 126 | let doc = utopia_store::documents::get(&state.pool, id).await?; |
| 127 | utopia_store::access::require_kb(&state.pool, &user, doc.kb_id, Role::Viewer).await?; |
| 128 | let chunks = utopia_store::documents::chunks_full(&state.pool, id).await?; |
| 129 | Ok(Json(json!({ "document": doc, "chunks": chunks }))) |
| 130 | } |
| 131 | |
| 132 | /// 反向证据链:文档各分块抽出的事实(文档查看器右栏)。 |
| 133 | pub async fn extractions( |
| 134 | State(state): State<AppState>, |
| 135 | AuthUser(user): AuthUser, |
| 136 | Path(id): Path<Uuid>, |
| 137 | ) -> ApiResult<Json<serde_json::Value>> { |
| 138 | let doc = utopia_store::documents::get(&state.pool, id).await?; |
| 139 | utopia_store::access::require_kb(&state.pool, &user, doc.kb_id, Role::Viewer).await?; |
| 140 | let facts = utopia_store::graph::document_extractions(&state.pool, id).await?; |
| 141 | Ok(Json(json!({ "facts": facts }))) |
| 142 | } |
| 143 | |
| 144 | pub async fn delete( |
| 145 | State(state): State<AppState>, |
| 146 | AuthUser(user): AuthUser, |
| 147 | Path(id): Path<Uuid>, |
| 148 | ) -> ApiResult<Json<serde_json::Value>> { |
| 149 | let doc = utopia_store::documents::get(&state.pool, id).await?; |
| 150 | utopia_store::access::require_kb(&state.pool, &user, doc.kb_id, Role::Editor).await?; |
| 151 | |
| 152 | utopia_store::documents::delete(&state.pool, id).await?; |
| 153 | let search = state.search.clone(); |
| 154 | let did = id.to_string(); |
| 155 | tokio::task::spawn_blocking(move || search.delete_document(&did)) |
| 156 | .await |
| 157 | .map_err(|e| AppError::Other(e.into()))? |
| 158 | .map_err(AppError::Other)?; |
| 159 | let _ = utopia_store::audit::record( |
| 160 | &state.pool, |
| 161 | Some(doc.kb_id), |
| 162 | user.id, |
| 163 | "document.deleted", |
| 164 | "document", |
| 165 | Some(id), |
| 166 | json!({ "filename": doc.filename }), |
| 167 | ) |
| 168 | .await; |
| 169 | Ok(Json(json!({ "ok": true }))) |
| 170 | } |
| 171 | |
| 172 | /// 重新处理(解析器升级/失败重试)。 |
| 173 | pub async fn reprocess( |
| 174 | State(state): State<AppState>, |
| 175 | AuthUser(user): AuthUser, |
| 176 | Path(id): Path<Uuid>, |
| 177 | ) -> ApiResult<Json<serde_json::Value>> { |
| 178 | let doc = utopia_store::documents::get(&state.pool, id).await?; |
| 179 | utopia_store::access::require_kb(&state.pool, &user, doc.kb_id, Role::Editor).await?; |
| 180 | utopia_store::documents::set_status(&state.pool, id, "pending").await?; |
| 181 | let job_id = utopia_store::jobs::enqueue( |
| 182 | &state.pool, |
| 183 | "process_document", |
| 184 | json!({ "document_id": id }), |
| 185 | ) |
| 186 | .await?; |
| 187 | Ok(Json(json!({ "job_id": job_id }))) |
| 188 | } |
| 189 | |
| 190 | fn hex(bytes: &[u8]) -> String { |
| 191 | bytes.iter().map(|b| format!("{b:02x}")).collect() |
| 192 | } |
| 193 | |
| 194 | /// 抽取丢弃信号:哪些事实抽出来了却没能落地。整库一次取回——按 |
| 195 | /// (文档 × 原因 × 具体对象) 聚合后行数很小,Library 既算总数又展开详情, |
| 196 | /// 不必逐行发请求。 |
| 197 | pub async fn extraction_drops( |
| 198 | State(state): State<AppState>, |
| 199 | AuthUser(user): AuthUser, |
| 200 | Path(kb_id): Path<Uuid>, |
| 201 | ) -> ApiResult<Json<serde_json::Value>> { |
| 202 | utopia_store::access::require_kb(&state.pool, &user, kb_id, Role::Viewer).await?; |
| 203 | let drops = utopia_store::extraction_drops::for_kb(&state.pool, kb_id).await?; |
| 204 | Ok(Json(json!({ "drops": drops }))) |
| 205 | } |