1use std::collections::BTreeMap;
62use std::sync::Arc;
63
64use anyhow::anyhow;
65use serde::{Deserialize, Serialize};
66use serde_json::Value;
67
68use super::User;
69use crate::db::{DateTime, Db, now};
70use crate::i18n::with_locale;
71use crate::mail::Mail;
72use crate::queue::{Job, JobContext};
73use crate::toast::{ToastAction, ToastKind};
74use crate::{AppState, Result};
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78#[non_exhaustive]
79pub enum Channel {
80 Mail,
82 Database,
85 Custom(&'static str),
88}
89
90#[derive(Debug, Clone, Default, Serialize, Deserialize)]
93#[non_exhaustive]
94pub struct Recipient {
95 user: Option<User>,
96 routes: BTreeMap<String, String>,
98 #[serde(default)]
100 language: Option<String>,
101}
102
103impl Recipient {
104 pub fn for_user(user: &User) -> Self {
106 Self {
107 user: Some(user.clone()),
108 routes: BTreeMap::new(),
109 language: None,
110 }
111 }
112
113 pub fn user(&self) -> Option<&User> {
115 self.user.as_ref()
116 }
117
118 pub fn to(channel: &str, address: impl Into<String>) -> Self {
120 Self::default().and(channel, address)
121 }
122
123 pub fn and(mut self, channel: &str, address: impl Into<String>) -> Self {
125 self.routes.insert(channel.to_owned(), address.into());
126 self
127 }
128
129 pub fn address(&self, channel: &str) -> Option<String> {
132 self.routes.get(channel).cloned().or_else(|| match channel {
133 "mail" => self.user.as_ref().map(|u| u.email.clone()),
134 _ => None,
135 })
136 }
137
138 pub(crate) fn has_address(&self, address: &str) -> bool {
140 self.routes.values().any(|a| a == address) || self.email().as_deref() == Some(address)
141 }
142
143 pub fn email(&self) -> Option<String> {
145 self.address("mail")
146 }
147
148 pub fn in_locale(mut self, locale: impl Into<String>) -> Self {
150 self.language = Some(locale.into());
151 self
152 }
153
154 pub fn locale(&self) -> Option<String> {
159 self.language.clone().or_else(|| {
160 self.user
161 .as_ref()?
162 .get::<String>("locale")
163 .filter(|l| !l.is_empty())
164 })
165 }
166}
167
168impl From<&User> for Recipient {
169 fn from(user: &User) -> Self {
170 Self::for_user(user)
171 }
172}
173
174impl From<&crate::AuthUser> for Recipient {
175 fn from(user: &crate::AuthUser) -> Self {
176 Self::for_user(user)
177 }
178}
179
180impl From<&Recipient> for Recipient {
181 fn from(recipient: &Recipient) -> Self {
182 recipient.clone()
183 }
184}
185
186pub trait Notification: Send + Sync {
188 fn kind(&self) -> &'static str;
190
191 fn channels(&self, to: &Recipient) -> Vec<Channel> {
195 let _ = to;
196 vec![Channel::Mail]
197 }
198
199 fn to_mail(&self, _to: &Recipient, _state: &AppState) -> Result<Mail> {
201 Err(anyhow!("notification `{}` has no mail version", self.kind()).into())
202 }
203
204 fn to_database(&self, to: &Recipient, state: &AppState) -> Result<Value> {
209 let _ = (to, state);
210 Ok(Value::Null)
211 }
212
213 fn to_channel(&self, channel: &str, to: &Recipient, state: &AppState) -> Result<Value> {
216 let _ = (to, state);
217 Err(anyhow!(
218 "notification `{}` has no version for the `{channel}` channel",
219 self.kind()
220 )
221 .into())
222 }
223}
224
225#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
231#[non_exhaustive]
232pub struct DatabaseMessage {
233 pub status: ToastKind,
235 pub title: String,
237 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub body: Option<String>,
240 #[serde(default, skip_serializing_if = "Option::is_none")]
242 pub url: Option<String>,
243 #[serde(default, skip_serializing_if = "Vec::is_empty")]
245 pub actions: Vec<ToastAction>,
246 #[serde(flatten)]
248 pub extra: serde_json::Map<String, Value>,
249}
250
251impl DatabaseMessage {
252 pub fn new(status: ToastKind, title: impl Into<String>) -> Self {
254 Self {
255 status,
256 title: title.into(),
257 body: None,
258 url: None,
259 actions: Vec::new(),
260 extra: serde_json::Map::new(),
261 }
262 }
263
264 pub fn success(title: impl Into<String>) -> Self {
266 Self::new(ToastKind::Success, title)
267 }
268
269 pub fn info(title: impl Into<String>) -> Self {
271 Self::new(ToastKind::Info, title)
272 }
273
274 pub fn warning(title: impl Into<String>) -> Self {
276 Self::new(ToastKind::Warning, title)
277 }
278
279 pub fn error(title: impl Into<String>) -> Self {
281 Self::new(ToastKind::Error, title)
282 }
283
284 pub fn body(mut self, body: impl Into<String>) -> Self {
286 self.body = Some(body.into());
287 self
288 }
289
290 pub fn url(mut self, url: impl Into<String>) -> Self {
292 self.url = Some(url.into());
293 self
294 }
295
296 pub fn action(mut self, action: ToastAction) -> Self {
298 self.actions.push(action);
299 self
300 }
301
302 pub fn link(self, label: impl Into<String>, url: impl Into<String>) -> Self {
304 self.action(ToastAction::link(label, url))
305 }
306
307 pub fn with(mut self, key: &str, value: impl Serialize) -> Self {
310 self.extra.insert(
311 key.to_owned(),
312 serde_json::to_value(value).unwrap_or(Value::Null),
313 );
314 self
315 }
316}
317
318impl From<DatabaseMessage> for Value {
319 fn from(message: DatabaseMessage) -> Self {
320 serde_json::to_value(message).unwrap_or(Value::Null)
321 }
322}
323
324#[derive(Debug, Clone, Serialize)]
326#[non_exhaustive]
327pub struct DatabaseNotification {
328 pub id: i64,
330 pub kind: String,
332 pub data: Value,
334 pub read_at: Option<DateTime>,
336 pub created_at: DateTime,
338}
339
340impl DatabaseNotification {
341 pub fn message(&self) -> Option<DatabaseMessage> {
344 serde_json::from_value(self.data.clone()).ok()
345 }
346}
347
348pub(crate) struct Hub {
354 tx: tokio::sync::broadcast::Sender<Signal>,
355}
356
357#[derive(Debug, Clone, PartialEq, Eq)]
358pub(crate) enum Signal {
359 User(i64),
361 Event(Option<i64>, Arc<Broadcast>),
363 Stop,
365}
366
367#[derive(Debug, PartialEq, Eq)]
370pub(crate) struct Broadcast {
371 pub(crate) event: String,
372 pub(crate) data: String,
373}
374
375impl Hub {
376 pub(crate) fn new() -> Self {
377 Self {
378 tx: tokio::sync::broadcast::channel(256).0,
379 }
380 }
381
382 pub(crate) fn touch(&self, user_id: i64) {
384 let _ = self.tx.send(Signal::User(user_id));
385 }
386
387 pub(crate) fn event(&self, user_id: Option<i64>, event: Broadcast) {
389 let _ = self.tx.send(Signal::Event(user_id, Arc::new(event)));
390 }
391
392 pub(crate) fn stop(&self) {
394 let _ = self.tx.send(Signal::Stop);
395 }
396
397 pub(crate) fn subscribe(&self) -> tokio::sync::broadcast::Receiver<Signal> {
398 self.tx.subscribe()
399 }
400}
401
402pub(crate) type ChannelFn = Arc<
403 dyn Fn(
404 AppState,
405 Recipient,
406 Value,
407 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result> + Send>>
408 + Send
409 + Sync,
410>;
411
412pub(crate) fn channel_fn<F, Fut>(send: F) -> ChannelFn
413where
414 F: Fn(Recipient, Value, AppState) -> Fut + Send + Sync + 'static,
415 Fut: std::future::Future<Output = Result> + Send + 'static,
416{
417 Arc::new(move |state, to, message| Box::pin(send(to, message, state)))
418}
419
420#[derive(Serialize, Deserialize)]
422pub(crate) struct SendToChannel {
423 channel: String,
424 to: Recipient,
425 message: Value,
426 #[serde(default, skip_serializing_if = "Option::is_none")]
428 limit: Option<crate::queue::Limit>,
429}
430
431impl Job for SendToChannel {
432 const NAME: &'static str = "renox.send-to-channel";
433 const MAX_ATTEMPTS: u32 = 5;
434
435 fn middleware(&self) -> Vec<crate::queue::Middleware> {
436 crate::queue::Limit::middleware(self.limit, format!("channel:{}", self.channel))
437 }
438
439 async fn handle(self, ctx: JobContext) -> Result {
440 let send = ctx.state.channel(&self.channel)?;
441 send(ctx.state.clone(), self.to, self.message).await
442 }
443}
444
445fn ordered(notification: &impl Notification, to: &Recipient) -> Vec<Channel> {
449 let mut channels = notification.channels(to);
450 channels.sort_by_key(|channel| match channel {
451 Channel::Database => 0,
452 Channel::Custom(_) => 1,
453 _ => 2,
454 });
455 channels
456}
457
458fn event_name(name: &str) -> Result<&str> {
461 let valid = !name.is_empty()
462 && name.len() <= 100
463 && name
464 .chars()
465 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | ':' | '.'));
466 if valid {
467 Ok(name)
468 } else {
469 Err(anyhow!(
470 "`{name}` can't be a broadcast event's name: use letters, digits, `-`, `_`, `:` and `.`"
471 )
472 .into())
473 }
474}
475
476impl AppState {
477 pub fn broadcast(&self, event: &str, data: impl Serialize) -> Result {
502 self.send_broadcast(None, event, data)
503 }
504
505 pub fn broadcast_to(&self, user_id: i64, event: &str, data: impl Serialize) -> Result {
507 self.send_broadcast(Some(user_id), event, data)
508 }
509
510 fn send_broadcast(&self, user_id: Option<i64>, event: &str, data: impl Serialize) -> Result {
511 let event = event_name(event)?.to_owned();
512 let data = serde_json::to_value(&data).map_err(anyhow::Error::from)?;
513 let sent = crate::SentBroadcast {
514 user_id,
515 event,
516 data,
517 };
518 if self.fakes.record_broadcast(sent.clone()) {
519 return Ok(());
520 }
521 self.notification_hub.event(
522 user_id,
523 Broadcast {
524 event: sent.event,
525 data: sent.data.to_string(),
526 },
527 );
528 Ok(())
529 }
530
531 pub(crate) fn channel(&self, name: &str) -> Result<ChannelFn> {
532 self.channels.get(name).cloned().ok_or_else(|| {
533 anyhow!("no `{name}` notification channel: register it with `App::channel`").into()
534 })
535 }
536
537 async fn store_notification(&self, to: &Recipient, notification: &impl Notification) -> Result {
538 let Some(user) = &to.user else { return Ok(()) };
540 crate::db::sql(
541 "INSERT INTO notifications (user_id, kind, data, created_at) VALUES (?, ?, ?, ?)",
542 )
543 .bind(user.id)
544 .bind(notification.kind())
545 .bind(
546 with_locale(to.locale().as_deref(), || {
547 notification.to_database(to, self)
548 })?
549 .to_string(),
550 )
551 .bind(now())
552 .execute(&self.db)
553 .await?;
554 self.notification_hub.touch(user.id);
555 Ok(())
556 }
557
558 pub async fn notify(
563 &self,
564 to: impl Into<Recipient>,
565 notification: &impl Notification,
566 ) -> Result {
567 let to = &to.into();
568 if self.fakes.record_notification(notification.kind(), to) {
569 return Ok(());
570 }
571 let locale = to.locale();
572 let locale = locale.as_deref();
573 for channel in ordered(notification, to) {
574 match channel {
575 Channel::Database => self.store_notification(to, notification).await?,
576 Channel::Custom(name) => {
577 let send = self.channel(name)?;
578 let message = with_locale(locale, || notification.to_channel(name, to, self))?;
579 send(self.clone(), to.clone(), message).await?;
580 }
581 Channel::Mail => {
582 let mail = with_locale(locale, || notification.to_mail(to, self))?;
583 self.mailer.send(mail).await?;
584 }
585 }
586 }
587 Ok(())
588 }
589
590 pub async fn notify_later(
594 &self,
595 to: impl Into<Recipient>,
596 notification: &impl Notification,
597 ) -> Result {
598 let to = to.into();
599 if self.fakes.record_notification(notification.kind(), &to) {
600 return Ok(());
601 }
602 let locale = to.locale();
603 let locale = locale.as_deref();
604 for channel in ordered(notification, &to) {
605 match channel {
606 Channel::Database => self.store_notification(&to, notification).await?,
607 Channel::Custom(name) => {
608 self.channel(name)?; let message = with_locale(locale, || notification.to_channel(name, &to, self))?;
610 self.dispatch(SendToChannel {
611 channel: name.to_owned(),
612 to: to.clone(),
613 message,
614 limit: self.channel_limits.get(name).copied(),
615 })
616 .await?;
617 }
618 Channel::Mail => {
619 let mail = with_locale(locale, || notification.to_mail(&to, self))?;
620 self.queue_mail(mail).await?;
621 }
622 }
623 }
624 Ok(())
625 }
626}
627
628pub(super) fn from_row(row: &crate::db::Row) -> Result<DatabaseNotification> {
629 let data: String = row.try_get("data")?;
630 Ok(DatabaseNotification {
631 id: row.try_get("id")?,
632 kind: row.try_get("kind")?,
633 data: serde_json::from_str(&data).unwrap_or(Value::Null),
634 read_at: row.try_get("read_at")?,
635 created_at: row.try_get("created_at")?,
636 })
637}
638
639impl User {
640 pub async fn notifications(&self, db: &Db, limit: u32) -> Result<Vec<DatabaseNotification>> {
642 let rows = crate::db::sql(
643 "SELECT id, kind, data, read_at, created_at FROM notifications \
644 WHERE user_id = ? ORDER BY id DESC LIMIT ?",
645 )
646 .bind(self.id)
647 .bind(i64::from(limit))
648 .fetch_all(db)
649 .await?;
650 rows.iter().map(from_row).collect()
651 }
652
653 pub async fn notifications_before(
656 &self,
657 db: &Db,
658 before: i64,
659 limit: u32,
660 ) -> Result<Vec<DatabaseNotification>> {
661 let rows = crate::db::sql(
662 "SELECT id, kind, data, read_at, created_at FROM notifications \
663 WHERE user_id = ? AND id < ? ORDER BY id DESC LIMIT ?",
664 )
665 .bind(self.id)
666 .bind(before)
667 .bind(i64::from(limit))
668 .fetch_all(db)
669 .await?;
670 rows.iter().map(from_row).collect()
671 }
672
673 pub async fn notification(&self, db: &Db, id: i64) -> Result<Option<DatabaseNotification>> {
675 let row = crate::db::sql(
676 "SELECT id, kind, data, read_at, created_at FROM notifications \
677 WHERE id = ? AND user_id = ?",
678 )
679 .bind(id)
680 .bind(self.id)
681 .fetch_optional(db)
682 .await?;
683 row.as_ref().map(from_row).transpose()
684 }
685
686 pub async fn unread_notifications(&self, db: &Db) -> Result<Vec<DatabaseNotification>> {
688 let rows = crate::db::sql(
689 "SELECT id, kind, data, read_at, created_at FROM notifications \
690 WHERE user_id = ? AND read_at IS NULL ORDER BY id DESC",
691 )
692 .bind(self.id)
693 .fetch_all(db)
694 .await?;
695 rows.iter().map(from_row).collect()
696 }
697
698 pub async fn unread_notification_count(&self, db: &Db) -> Result<i64> {
700 Ok(crate::db::sql(
701 "SELECT COUNT(*) FROM notifications WHERE user_id = ? AND read_at IS NULL",
702 )
703 .bind(self.id)
704 .scalar(db)
705 .await?)
706 }
707
708 pub async fn mark_notification_read(&self, db: &Db, id: i64) -> Result<bool> {
710 let done = crate::db::sql(
711 "UPDATE notifications SET read_at = COALESCE(read_at, ?) WHERE id = ? AND user_id = ?",
712 )
713 .bind(now())
714 .bind(id)
715 .bind(self.id)
716 .execute(db)
717 .await?;
718 Ok(done > 0)
719 }
720
721 pub async fn mark_notification_unread(&self, db: &Db, id: i64) -> Result<bool> {
724 let done =
725 crate::db::sql("UPDATE notifications SET read_at = NULL WHERE id = ? AND user_id = ?")
726 .bind(id)
727 .bind(self.id)
728 .execute(db)
729 .await?;
730 Ok(done > 0)
731 }
732
733 pub async fn delete_notification(&self, db: &Db, id: i64) -> Result<bool> {
735 let done = crate::db::sql("DELETE FROM notifications WHERE id = ? AND user_id = ?")
736 .bind(id)
737 .bind(self.id)
738 .execute(db)
739 .await?;
740 Ok(done > 0)
741 }
742
743 pub async fn delete_notifications(&self, db: &Db) -> Result<u64> {
745 Ok(
746 crate::db::sql("DELETE FROM notifications WHERE user_id = ?")
747 .bind(self.id)
748 .execute(db)
749 .await?,
750 )
751 }
752
753 pub async fn mark_all_notifications_read(&self, db: &Db) -> Result<u64> {
755 let done = crate::db::sql(
756 "UPDATE notifications SET read_at = ? WHERE user_id = ? AND read_at IS NULL",
757 )
758 .bind(now())
759 .bind(self.id)
760 .execute(db)
761 .await?;
762 Ok(done)
763 }
764}
765
766pub async fn prune_read_notifications(db: &Db, age: std::time::Duration) -> Result<u64> {
771 let before = now() - chrono::Duration::from_std(age).unwrap_or_default();
772 Ok(
773 crate::db::sql("DELETE FROM notifications WHERE read_at < ?")
774 .bind(before)
775 .execute(db)
776 .await?,
777 )
778}