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,
};
use maud::{html, PreEscaped, DOCTYPE};
use maud::{html, Markup, PreEscaped, DOCTYPE};
use reqwest::Client;
use serde_json::json;
use sqlx::SqliteConnection;
@ -118,7 +118,7 @@ impl From<&MtForm> for HashMap<i32, String> {
}
impl MtForm {
async fn build_email(&self) -> PreEscaped<std::string::String> {
async fn build_email(&self) -> Markup {
html! {
(DOCTYPE)
meta charset="utf-8";
@ -272,8 +272,9 @@ impl MtForm {
let client = Client::new();
let map = HashMap::from(self);
let mut json = HashMap::new();
dbg!(&map);
json.insert("data", map);
let link = r#"https://staff.tfcconnection.org/apps/tables/#/table/9/row/757"#;
let res = client
.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"))
@ -282,10 +283,8 @@ impl MtForm {
.json(&json)
.send()
.await?;
dbg!(&res);
if res.status().is_success() {
let res = res.text().await.unwrap();
dbg!(res);
Ok(())
} else {
Err(eyre!(
@ -294,74 +293,91 @@ impl MtForm {
))
}
}
}
#[post("/api/mt-form")]
pub async fn mt_form(MultipartForm(form): MultipartForm<MtForm>) -> HttpResponse {
let first = form.first_name.clone();
let last = form.last_name.clone();
let filename_noext = format!("{}_{}", first, last);
let email_subject = format!("{} {} signed up for mission trip!", first, last);
info!("{first} {last} signed up for mission trip!");
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() {
fn get_temp_file(&mut self) -> Option<(String, String)> {
let first = self.first_name.clone();
let last = self.last_name.clone();
let filename_noext = format!("{}_{}", first, last);
let file_name = if let Some(file) = self.file.as_ref() {
file.file_name.to_owned()
} else {
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);
path = format!("./tmp/{}.{}", filename_noext, ext);
format!("./tmp/{}.{}", filename_noext, ext)
} else {
path = format!("./tmp/{}", file_str);
filename = String::default();
format!("./tmp/{}", file_name)
}
info!("saving to {}", path);
match file.file.persist(&path) {
Ok(f) => {
if f.metadata().unwrap().len() > 0 {
file_exists = true;
}
info!(?f, "File saved successfully");
} else {
filename = String::default();
String::default()
};
let file = self.file.take();
match file.unwrap().file.persist(path.clone()) {
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 {
let filebody = fs::read(path);
let content_type = ContentType::parse("image/jpg").unwrap();
let attachment = Attachment::new(filename).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())
};
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 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()
.from(
"TFC ADMIN <no-reply@mail.tfcconnection.org>"
.parse()
.unwrap(),
)
.to("Chris Cochrun <chris@tfcconnection.org>".parse().unwrap())
.subject(email_subject)
.multipart(multi)
{
let future = crate::email::send_email(m);
actix_rt::spawn(future);
} else {
error!("Email incorrect");
if let Ok(m) = Message::builder()
.from(
"TFC ADMIN <no-reply@mail.tfcconnection.org>"
.parse()
.unwrap(),
)
.to("Chris Cochrun <chris@tfcconnection.org>".parse().unwrap())
.subject(email_subject)
.multipart(multi)
{
crate::email::send_email(m).await
} else {
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")
}
@ -418,14 +434,20 @@ mod test {
async fn test_nc_post() {
let form = form();
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;
match res {
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}"),
}
}
}