Skip to content

Commit

Permalink
feat: send emails
Browse files Browse the repository at this point in the history
  • Loading branch information
Rustin170506 committed Apr 5, 2024
1 parent bb5a78d commit 6195dff
Showing 1 changed file with 36 additions and 5 deletions.
41 changes: 36 additions & 5 deletions src/worker/jobs/expiry_notification.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::sync::Arc;
use diesel::{Connection, PgConnection};

use crate::{email::Email, models::User, worker::Environment, Emails};
use anyhow::anyhow;
use crates_io_worker::BackgroundJob;
use crate::Emails;
use crate::worker::Environment;
use diesel::{
dsl::now, Connection, ExpressionMethods, NullableExpressionMethods, PgConnection, RunQueryDsl,
};
use std::sync::Arc;

/// The threshold in days for the expiry notification.
const EXPIRY_THRESHOLD: i64 = 3;
Expand Down Expand Up @@ -38,10 +39,40 @@ fn check(emails: &Emails, conn: &mut PgConnection) -> anyhow::Result<()> {
conn.transaction(|conn| {
for token in chunk {
// Send notification.
let user = User::find(conn, token.user_id)?;
let Some(recipient) = user.email(conn)? else {
return Err(anyhow!("No address found"));
};
let email = ExpiryNotificationEmail {
token_name: token.name.clone(),
expiry_date: token.expired_at.unwrap().date().to_string(),
};
emails.send(&recipient, email)?;
// Also update the token to prevent duplicate notifications.
diesel::update(token)
.set(crate::schema::api_tokens::expiry_notification_at.eq(now.nullable()))
.execute(conn)?;
}
Ok::<_, anyhow::Error>(())
})?;
}

Ok(())
}

#[derive(Debug, Clone)]
struct ExpiryNotificationEmail {
token_name: String,
expiry_date: String,
}

impl Email for ExpiryNotificationEmail {
const SUBJECT: &'static str = "Token Expiry Notification";

fn body(&self) -> String {
format!(
"The token {} is about to expire on {}. Please take action.",
self.token_name, self.expiry_date
)
}
}

0 comments on commit 6195dff

Please sign in to comment.