use std::sync::{Arc, Mutex, RwLock};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Purpose {
Verify,
Reset,
EmailChange,
Invitation,
AccountExists,
Notice,
}
#[derive(Clone, Debug)]
pub struct Mail {
pub to: String,
pub subject: String,
pub text: String,
pub purpose: Purpose,
pub token: String,
}
pub trait Mailer: Send + Sync {
fn send(&self, mail: Mail);
}
pub struct ConsoleMailer;
impl Mailer for ConsoleMailer {
fn send(&self, mail: Mail) {
eprintln!("mail to {}: {}\n{}", mail.to, mail.subject, mail.text);
}
}
#[derive(Default)]
pub struct MemoryMailer {
pub sent: Mutex<Vec<Mail>>,
}
impl MemoryMailer {
pub fn last(&self, to: &str) -> Option<Mail> {
self.sent
.lock()
.unwrap()
.iter()
.rev()
.find(|m| m.to == to)
.cloned()
}
}
impl Mailer for MemoryMailer {
fn send(&self, mail: Mail) {
self.sent.lock().unwrap().push(mail);
}
}
static MAILER: RwLock<Option<Arc<dyn Mailer>>> = RwLock::new(None);
pub fn use_mailer(mailer: Arc<dyn Mailer>) {
*MAILER.write().unwrap() = Some(mailer);
}
pub fn current_mailer() -> Arc<dyn Mailer> {
MAILER
.read()
.unwrap()
.clone()
.unwrap_or_else(|| Arc::new(ConsoleMailer))
}