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,50 +293,56 @@ 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 email_subject = format!("{} {} signed up for mission trip!", first, last); let file_name = if let Some(file) = self.file.as_ref() {
info!("{first} {last} signed up for mission trip!"); file.file_name.to_owned()
let email = form.build_email().await;
let mut path = String::from("");
let mut file_exists = false;
let mut filename = String::from("");
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);
path = format!("./tmp/{}.{}", filename_noext, ext);
} else { } else {
path = format!("./tmp/{}", file_str); return None;
};
let filename;
let path = if let Some(file_name) = file_name {
if let Some(ext) = file_name.rsplit('.').next() {
filename = format!("{}.{}", filename_noext, ext);
format!("./tmp/{}.{}", filename_noext, ext)
} else {
filename = String::default();
format!("./tmp/{}", file_name)
} }
info!("saving to {}", path); } else {
match file.file.persist(&path) { filename = String::default();
String::default()
};
let file = self.file.take();
match file.unwrap().file.persist(path.clone()) {
Ok(f) => { Ok(f) => {
if f.metadata().unwrap().len() > 0 { if f.metadata().unwrap().len() <= 0 {
file_exists = true; return None;
} }
info!(?f, "File saved successfully"); info!(?f, "File saved successfully");
Some((filename, path))
} }
Err(e) => info!("{:?}: Probably a missing image", e), Err(e) => {
error!("{:?}: Probably a missing image", e);
None
} }
} }
} }
let multi = if file_exists { async fn send_email(&mut self) -> Result<()> {
let first = self.first_name.clone();
let last = self.last_name.clone();
let email_subject = format!("{} {} signed up for mission trip!", first, last);
info!("{first} {last} signed up for mission trip!");
let email = self.build_email().await;
let temp_file = self.get_temp_file();
let multi = if let Some((file, path)) = temp_file {
let filebody = fs::read(path); let filebody = fs::read(path);
let content_type = ContentType::parse("image/jpg").unwrap(); let content_type = ContentType::parse("image/jpg").unwrap();
let attachment = Attachment::new(filename).body(filebody.unwrap(), content_type); let attachment = Attachment::new(file).body(filebody.unwrap(), content_type);
// info!(?attachment); // info!(?attachment);
MultiPart::mixed() MultiPart::mixed()
.singlepart(SinglePart::html(email.into_string())) .singlepart(SinglePart::html(email.into_string()))
@ -356,12 +361,23 @@ pub async fn mt_form(MultipartForm(form): MultipartForm<MtForm>) -> HttpResponse
.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 {
error!("Email incorrect"); Err(eyre!("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}"),
} }
} }
} }