making health forms more asynchronous

This commit is contained in:
Chris Cochrun 2024-12-24 22:26:01 -06:00
parent a9d2a043a6
commit 19c6ec1ff7

View file

@ -2,7 +2,11 @@ use std::{collections::HashMap, fs};
use actix_multipart::form::{tempfile::TempFile, text::Text, MultipartForm};
use actix_web::{post, HttpResponse};
use color_eyre::{eyre::eyre, Result};
use color_eyre::{
eyre::{eyre, Context},
Result,
};
use futures::FutureExt;
use lettre::{
message::{header::ContentType, Attachment, MultiPart, SinglePart},
Message,
@ -110,7 +114,7 @@ impl From<&HealthForm> for HashMap<i32, String> {
}
impl HealthForm {
async fn build_email(&self) -> Markup {
fn build_email(&self) -> Markup {
html! {
(DOCTYPE)
meta charset="utf-8";
@ -312,12 +316,12 @@ impl HealthForm {
}
}
async fn send_email(&mut self) -> Result<()> {
fn send_email(&mut self) -> Result<Message> {
let first = self.first_name.clone();
let last = self.last_name.clone();
let email_subject = format!("{} {} filled out a health form!", first, last);
info!("{first} {last} filled out a health form!");
let email = self.build_email().await;
let email = self.build_email();
let temp_file = self.get_temp_file();
let multi = if let Some((file, path, content_type)) = temp_file {
let filebody = fs::read(path);
@ -332,7 +336,7 @@ impl HealthForm {
MultiPart::alternative_plain_html(String::from("Testing"), email.into_string())
};
if let Ok(m) = Message::builder()
Message::builder()
.from(
"TFC ADMIN <no-reply@mail.tfcconnection.org>"
.parse()
@ -342,19 +346,21 @@ impl HealthForm {
// .to("Ethan Rose <ethan@tfcconnection.org>".parse().unwrap())
.subject(email_subject)
.multipart(multi)
{
send_email(m).await
} else {
Err(eyre!("Email incorrect"))
}
.wrap_err("Email incorrect")
}
}
#[post("/api/health-form")]
pub async fn health_form(MultipartForm(mut form): MultipartForm<HealthForm>) -> HttpResponse {
info!("Starting health form work: {:?}", form);
match form.send_email().await {
Ok(_) => info!("Successfully sent email health form"),
match form.send_email() {
Ok(m) => {
actix_rt::spawn(send_email(m).map(|r| match r {
Ok(_) => info!("Email sent successfully"),
Err(e) => error!("There was an erroring sending form to nextcloud: {e}"),
}));
info!("Successfully sent email health form")
}
Err(e) => error!("There was an error sending email: {e}"),
}