|
| 1 | +use crate::authentication::UserId; |
| 2 | +use crate::domain::SubscriberEmail; |
| 3 | +use crate::email_client::EmailClient; |
| 4 | +use crate::utils::{e500, see_other}; |
| 5 | +use actix_web::web::ReqData; |
| 6 | +use actix_web::{web, HttpResponse}; |
| 7 | +use actix_web_flash_messages::FlashMessage; |
| 8 | +use anyhow::Context; |
| 9 | +use sqlx::PgPool; |
| 10 | + |
| 11 | +#[derive(serde::Deserialize)] |
| 12 | +pub struct BodyData { |
| 13 | + title: String, |
| 14 | + content: Content, |
| 15 | +} |
| 16 | + |
| 17 | +#[derive(serde::Deserialize)] |
| 18 | +pub struct Content { |
| 19 | + html: String, |
| 20 | + text: String, |
| 21 | +} |
| 22 | + |
| 23 | +#[tracing::instrument( |
| 24 | +name = "Publish a newsletter issue", |
| 25 | + skip(body, pool, email_client, user_id), |
| 26 | + fields(user_id = %*user_id) |
| 27 | +)] |
| 28 | +pub async fn publish_newsletter( |
| 29 | + body: web::Form<BodyData>, |
| 30 | + pool: web::Data<PgPool>, |
| 31 | + email_client: web::Data<EmailClient>, |
| 32 | + user_id: ReqData<UserId>, |
| 33 | +) -> Result<HttpResponse, actix_web::Error> { |
| 34 | + let subscribers = get_confirmed_subscribers(&pool).await.map_err(e500)?; |
| 35 | + for subscriber in subscribers { |
| 36 | + match subscriber { |
| 37 | + Ok(subscriber) => { |
| 38 | + email_client |
| 39 | + .send_email( |
| 40 | + &subscriber.email, |
| 41 | + &body.title, |
| 42 | + &body.content.html, |
| 43 | + &body.content.text, |
| 44 | + ) |
| 45 | + .await |
| 46 | + .with_context(|| { |
| 47 | + format!("Failed to send newsletter issue to {}", subscriber.email) |
| 48 | + }).map_err(e500)?; |
| 49 | + } |
| 50 | + Err(error) => { |
| 51 | + tracing::warn!( |
| 52 | + error.cause_chain = ?error, |
| 53 | + error.message = %error, |
| 54 | + "Skipping a confirmed subscriber. \ |
| 55 | + Their stored contact details are invalid", |
| 56 | + ); |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + FlashMessage::info("The newsletter issue has been published!").send(); |
| 61 | + Ok(see_other("/admin/newsletters")) |
| 62 | +} |
| 63 | + |
| 64 | +struct ConfirmedSubscriber { |
| 65 | + email: SubscriberEmail, |
| 66 | +} |
| 67 | + |
| 68 | +#[tracing::instrument(name = "Get confirmed subscribers", skip(pool))] |
| 69 | +async fn get_confirmed_subscribers( |
| 70 | + pool: &PgPool, |
| 71 | +) -> Result<Vec<Result<ConfirmedSubscriber, anyhow::Error>>, anyhow::Error> { |
| 72 | + let confirmed_subscribers = sqlx::query!( |
| 73 | + r#" |
| 74 | + SELECT email |
| 75 | + FROM subscriptions |
| 76 | + WHERE status = 'confirmed' |
| 77 | + "#, |
| 78 | + ) |
| 79 | + .fetch_all(pool) |
| 80 | + .await? |
| 81 | + .into_iter() |
| 82 | + .map(|r| match SubscriberEmail::parse(r.email) { |
| 83 | + Ok(email) => Ok(ConfirmedSubscriber { email }), |
| 84 | + Err(error) => Err(anyhow::anyhow!(error)), |
| 85 | + }) |
| 86 | + .collect(); |
| 87 | + Ok(confirmed_subscribers) |
| 88 | +} |
0 commit comments