Skip to content

Commit

Permalink
Added knowledge base
Browse files Browse the repository at this point in the history
  • Loading branch information
dialogflowchatbot committed Sep 29, 2024
1 parent cbc6a33 commit 8f43488
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 15 deletions.
48 changes: 33 additions & 15 deletions src/kb/crud.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,44 @@
use axum::{extract::Multipart, response::IntoResponse};
use std::path::Path;

use crate::result::Error;
use axum::{extract::{Multipart, Query}, response::IntoResponse};

use crate::result::{Error, Result};
use crate::robot::dto::RobotQuery;
use crate::web::server::to_res;

pub(crate) async fn upload(mut multipart: Multipart) -> impl IntoResponse {
pub(crate) async fn upload(Query(q):Query<RobotQuery>,multipart: Multipart) -> impl IntoResponse {
if let Err(e) = do_upload(&q.robot_id,multipart).await {
return to_res(Err(e));
}
to_res(Ok(()))
}

async fn do_upload(robot_id:&str,mut multipart: Multipart) -> Result<()> {
let p = Path::new(".").join("data").join("kb").join("docs").join("upload").join(robot_id);
if !p.exists() {
std::fs::create_dir_all(&p)?;
}
loop {
let r = multipart.next_field().await;
if r.is_err() {
let m = format!("Upload failed, err: {:?}.", r.unwrap_err());
return to_res(Err(Error::ErrorWithMessage(m)));
}
let field = r.unwrap();
let field = multipart.next_field().await?;
if field.is_none() {
return to_res(Ok("Upload successfully."));
return Ok(());
}
let field = field.unwrap();
let name = field.name().unwrap().to_string();
let file_name = field.file_name().unwrap().to_string();
let content_type = field.content_type().unwrap().to_string();
let data = field.bytes().await.unwrap();
let Some(name) = field.name() else {
return Err(Error::ErrorWithMessage(String::from("Name is missing.")));
};
let name = name.to_string();
let Some(file_name) = field.file_name() else {
return Err(Error::ErrorWithMessage(String::from("File name is missing.")))
};
let file_name = file_name.to_string();
let Some(content_type) = field.content_type() else {
return Err(Error::ErrorWithMessage(String::from("Content type is missing.")))
};
let content_type = content_type.to_string();
let data = field.bytes().await?;

println!(
log::info!(
"Length of `{name}` (`{file_name}`: `{content_type}`) is {} bytes",
data.len()
);
Expand Down
6 changes: 6 additions & 0 deletions src/result/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,3 +188,9 @@ impl From<tokio::task::JoinError> for Error {
Error::ErrorWithMessage(format!("Thread join error: {:?}", err))
}
}

impl From<axum::extract::multipart::MultipartError> for Error {
fn from(err: axum::extract::multipart::MultipartError) -> Self {
Error::ErrorWithMessage(format!("Multipart error: {:?}", err))
}
}

0 comments on commit 8f43488

Please sign in to comment.