form is working to store nextcloud stuff now

This commit is contained in:
Chris Cochrun 2024-11-12 10:01:16 -06:00
parent 87c0d9cb01
commit e934788259

View file

@ -10,7 +10,7 @@ use lettre::{
message::{header::ContentType, Attachment, MultiPart, SinglePart}, message::{header::ContentType, Attachment, MultiPart, SinglePart},
Message, Message,
}; };
use maud::{html, PreEscaped, DOCTYPE}; use maud::{html, Markup, PreEscaped, DOCTYPE};
use reqwest::Client; use reqwest::Client;
use serde_json::json; use serde_json::json;
use sqlx::SqliteConnection; use sqlx::SqliteConnection;
@ -118,7 +118,7 @@ impl From<&MtForm> for HashMap<i32, String> {
} }
impl MtForm { impl MtForm {
async fn build_email(&self) -> PreEscaped<std::string::String> { async fn build_email(&self) -> Markup {
html! { html! {
(DOCTYPE) (DOCTYPE)
meta charset="utf-8"; meta charset="utf-8";
@ -272,8 +272,9 @@ impl MtForm {
let client = Client::new(); let client = Client::new();
let map = HashMap::from(self); let map = HashMap::from(self);
let mut json = HashMap::new(); let mut json = HashMap::new();
dbg!(&map);
json.insert("data", map); json.insert("data", map);
let link = r#"https://staff.tfcconnection.org/apps/tables/#/table/9/row/757"#;
let res = client let res = client
.post("https://staff.tfcconnection.org/ocs/v2.php/apps/tables/api/2/tables/9/rows") .post("https://staff.tfcconnection.org/ocs/v2.php/apps/tables/api/2/tables/9/rows")
.basic_auth("chris", Some("2VHeGxeC^Zf9KqFK^G@Pt!zu2q^6@b")) .basic_auth("chris", Some("2VHeGxeC^Zf9KqFK^G@Pt!zu2q^6@b"))
@ -282,10 +283,8 @@ impl MtForm {
.json(&json) .json(&json)
.send() .send()
.await?; .await?;
dbg!(&res);
if res.status().is_success() { if res.status().is_success() {
let res = res.text().await.unwrap(); let res = res.text().await.unwrap();
dbg!(res);
Ok(()) Ok(())
} else { } else {
Err(eyre!( Err(eyre!(
@ -294,74 +293,91 @@ impl MtForm {
)) ))
} }
} }
}
#[post("/api/mt-form")] fn get_temp_file(&mut self) -> Option<(String, String)> {
pub async fn mt_form(MultipartForm(form): MultipartForm<MtForm>) -> HttpResponse { let first = self.first_name.clone();
let first = form.first_name.clone(); let last = self.last_name.clone();
let last = form.last_name.clone(); let filename_noext = format!("{}_{}", first, last);
let filename_noext = format!("{}_{}", first, last); let file_name = if let Some(file) = self.file.as_ref() {
let email_subject = format!("{} {} signed up for mission trip!", first, last); file.file_name.to_owned()
info!("{first} {last} signed up for mission trip!"); } else {
let email = form.build_email().await; return None;
let mut path = String::from(""); };
let mut file_exists = false; let filename;
let mut filename = String::from(""); let path = if let Some(file_name) = file_name {
if let Some(ext) = file_name.rsplit('.').next() {
match form.store_form().await {
Ok(_) => info!("Successfully sent form to nextcloud!"),
Err(e) => error!("There was an erroring sending form to nextcloud: {}", e),
}
if let Some(file) = form.file {
if let Some(file_str) = file.file_name {
if let Some(ext) = file_str.rsplit('.').next() {
filename = format!("{}.{}", filename_noext, ext); filename = format!("{}.{}", filename_noext, ext);
path = format!("./tmp/{}.{}", filename_noext, ext); format!("./tmp/{}.{}", filename_noext, ext)
} else { } else {
path = format!("./tmp/{}", file_str); filename = String::default();
format!("./tmp/{}", file_name)
} }
info!("saving to {}", path); } else {
match file.file.persist(&path) { filename = String::default();
Ok(f) => { String::default()
if f.metadata().unwrap().len() > 0 { };
file_exists = true; let file = self.file.take();
} match file.unwrap().file.persist(path.clone()) {
info!(?f, "File saved successfully"); Ok(f) => {
if f.metadata().unwrap().len() <= 0 {
return None;
} }
Err(e) => info!("{:?}: Probably a missing image", e), info!(?f, "File saved successfully");
Some((filename, path))
}
Err(e) => {
error!("{:?}: Probably a missing image", e);
None
} }
} }
} }
let multi = if file_exists { async fn send_email(&mut self) -> Result<()> {
let filebody = fs::read(path); let first = self.first_name.clone();
let content_type = ContentType::parse("image/jpg").unwrap(); let last = self.last_name.clone();
let attachment = Attachment::new(filename).body(filebody.unwrap(), content_type); let email_subject = format!("{} {} signed up for mission trip!", first, last);
// info!(?attachment); info!("{first} {last} signed up for mission trip!");
MultiPart::mixed() let email = self.build_email().await;
.singlepart(SinglePart::html(email.into_string())) let temp_file = self.get_temp_file();
.singlepart(attachment) let multi = if let Some((file, path)) = temp_file {
} else { let filebody = fs::read(path);
MultiPart::alternative_plain_html(String::from("Testing"), email.into_string()) let content_type = ContentType::parse("image/jpg").unwrap();
}; let attachment = Attachment::new(file).body(filebody.unwrap(), content_type);
// info!(?attachment);
MultiPart::mixed()
.singlepart(SinglePart::html(email.into_string()))
.singlepart(attachment)
} else {
MultiPart::alternative_plain_html(String::from("Testing"), email.into_string())
};
if let Ok(m) = Message::builder() if let Ok(m) = Message::builder()
.from( .from(
"TFC ADMIN <no-reply@mail.tfcconnection.org>" "TFC ADMIN <no-reply@mail.tfcconnection.org>"
.parse() .parse()
.unwrap(), .unwrap(),
) )
.to("Chris Cochrun <chris@tfcconnection.org>".parse().unwrap()) .to("Chris Cochrun <chris@tfcconnection.org>".parse().unwrap())
.subject(email_subject) .subject(email_subject)
.multipart(multi) .multipart(multi)
{ {
let future = crate::email::send_email(m); crate::email::send_email(m).await
actix_rt::spawn(future); } else {
} else { Err(eyre!("Email incorrect"))
error!("Email incorrect"); }
} }
}
#[post("/api/mt-form")]
pub async fn mt_form(MultipartForm(mut form): MultipartForm<MtForm>) -> HttpResponse {
match form.store_form().await {
Ok(_) => info!("Successfully sent form to nextcloud!"),
Err(e) => error!("There was an erroring sending form to nextcloud: {e}"),
}
match form.send_email().await {
Ok(_) => info!("Successfully sent email"),
Err(e) => error!("There was an error sending the email: {e}"),
}
HttpResponse::Ok().body("thankyou") HttpResponse::Ok().body("thankyou")
} }
@ -418,14 +434,20 @@ mod test {
async fn test_nc_post() { async fn test_nc_post() {
let form = form(); let form = form();
assert!(!form.first_name.is_empty()); assert!(!form.first_name.is_empty());
dbg!(&form);
// let conn = SqliteConnection::connect("file://./data.db")
// .await
// .expect("Couldn't connect sqlite db");
let res = form.store_form().await; let res = form.store_form().await;
match res { match res {
Ok(_) => assert!(true, "passed storing test"), Ok(_) => assert!(true, "passed storing test"),
Err(e) => assert!(false, "Failed storing test: {}", e), Err(e) => assert!(false, "Failed storing test: {e}"),
}
}
#[test]
async fn test_email() {
let mut form = form();
assert!(!form.first_name.is_empty());
match form.send_email().await {
Ok(_) => assert!(true, "passed emailing test"),
Err(e) => assert!(false, "Failed emailing test: {e}"),
} }
} }
} }