capy_mail/
notifications.rs1use crate::{DeliveryReceipt, Mail, MailResult, Mailbox, Mailer};
3
4pub trait MailRecipient {
6 fn mail_address(&self) -> Option<Mailbox>;
8}
9impl MailRecipient for Mailbox {
10 fn mail_address(&self) -> Option<Mailbox> {
11 Some(self.clone())
12 }
13}
14pub trait Notification: Send + Sync {
16 const NAME: &'static str;
18 fn mail(&self, recipient: &Mailbox) -> MailResult<Option<Mail>>;
20}
21pub trait QueueableNotification: Notification {}
23impl Mailer {
24 pub async fn notify<N: Notification>(
26 &self,
27 recipient: &impl MailRecipient,
28 notification: N,
29 ) -> MailResult<Option<DeliveryReceipt>> {
30 let Some(route) = recipient.mail_address() else {
31 return Ok(None);
32 };
33 let Some(mail) = notification.mail(&route)? else {
34 return Ok(None);
35 };
36 self.send_mail(N::NAME, mail.to(route)).await.map(Some)
37 }
38 #[cfg(feature = "jobs")]
40 pub async fn queue_notification<N: QueueableNotification>(
41 &self,
42 ctx: &impl capy_jobs::JobDispatch,
43 recipient: &impl MailRecipient,
44 notification: N,
45 ) -> MailResult<Option<String>> {
46 self.queue_notification_in(ctx, None, recipient, notification)
47 .await
48 }
49 #[cfg(feature = "jobs")]
51 pub async fn queue_notification_in<N: QueueableNotification>(
52 &self,
53 ctx: &impl capy_jobs::JobDispatch,
54 transaction: Option<&sea_orm::DatabaseTransaction>,
55 recipient: &impl MailRecipient,
56 notification: N,
57 ) -> MailResult<Option<String>> {
58 let Some(route) = recipient.mail_address() else {
59 return Ok(None);
60 };
61 let Some(mail) = notification.mail(&route)? else {
62 return Ok(None);
63 };
64 let queue = ctx
65 .jobs()
66 .queue(self.settings.queue.clone())
67 .map_err(|_| crate::MailError::Configuration)?;
68 self.queue_rendered(&queue, transaction, N::NAME, mail.to(route))
69 .await
70 .map(Some)
71 }
72}