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 let Some(route) = recipient.mail_address() else {
47 return Ok(None);
48 };
49 let Some(mail) = notification.mail(&route)? else {
50 return Ok(None);
51 };
52 let queue = ctx
53 .jobs()
54 .queue(self.settings.queue.clone())
55 .map_err(|_| crate::MailError::Configuration)?;
56 self.queue_rendered(
57 crate::queued::QueueTarget::Pool(&queue),
58 N::NAME,
59 mail.to(route),
60 )
61 .await
62 .map(Some)
63 }
64 #[cfg(feature = "jobs")]
66 pub async fn queue_notification_in<N: QueueableNotification>(
67 &self,
68 transaction: &sea_orm::DatabaseTransaction,
69 recipient: &impl MailRecipient,
70 notification: N,
71 ) -> MailResult<Option<String>> {
72 let Some(route) = recipient.mail_address() else {
73 return Ok(None);
74 };
75 let Some(mail) = notification.mail(&route)? else {
76 return Ok(None);
77 };
78 let queue = capy_jobs::TransactionalQueue::new(transaction)
79 .queue(self.settings.queue.clone())
80 .map_err(|_| crate::MailError::Configuration)?;
81 self.queue_rendered(
82 crate::queued::QueueTarget::Transaction(queue),
83 N::NAME,
84 mail.to(route),
85 )
86 .await
87 .map(Some)
88 }
89}