Skip to main content

renox_core/auth/
notifications.rs

1//! Notifications: one message to a user (or to an address), delivered by
2//! email, stored for an in-app list, sent through the app's own channels
3//! (WhatsApp, SMS, Slack…), or all of these.
4//!
5//! ```
6//! # use renox::prelude::*;
7//! use renox::auth::{Channel, DatabaseMessage, Notification, Recipient};
8//! use renox::mail::Mail;
9//!
10//! struct OrderShipped { order_id: i64 }
11//!
12//! impl Notification for OrderShipped {
13//!     fn kind(&self) -> &'static str { "order-shipped" }
14//!     // Per recipient, like Laravel's `via`: WhatsApp only for those with a number.
15//!     fn channels(&self, to: &Recipient) -> Vec<Channel> {
16//!         let mut channels = vec![Channel::Mail, Channel::Database];
17//!         if to.address("whatsapp").is_some() {
18//!             channels.push(Channel::Custom("whatsapp"));
19//!         }
20//!         channels
21//!     }
22//!
23//!     fn to_mail(&self, to: &Recipient, state: &AppState) -> Result<Mail> {
24//!         let email = to.email().unwrap_or_default();
25//!         state.mail_view(&email, "Your order has shipped", "mail/shipped", context! { id => self.order_id })
26//!     }
27//!
28//!     // What the in-app list (the UI kit's `notification_bell`) shows.
29//!     fn to_database(&self, _: &Recipient, _: &AppState) -> Result<renox::serde_json::Value> {
30//!         Ok(DatabaseMessage::success(format!("Order #{} shipped", self.order_id))
31//!             .body("It arrives in 2–3 days.")
32//!             .url(format!("/orders/{}", self.order_id))
33//!             .with("order_id", self.order_id) // any other keys the app reads back
34//!             .into())
35//!     }
36//!
37//!     fn to_channel(&self, _channel: &str, _: &Recipient, _: &AppState) -> Result<renox::serde_json::Value> {
38//!         Ok(json!({ "text": format!("Order #{} has shipped", self.order_id) }))
39//!     }
40//! }
41//!
42//! # async fn demo(state: AppState, user: User, db: Db, order_id: i64) -> Result {
43//! state.notify(&user, &OrderShipped { order_id }).await?;          // now
44//! state.notify_later(&user, &OrderShipped { order_id }).await?;    // through the queue
45//! // Someone without an account:
46//! let guest = Recipient::to("mail", "guest@example.com").and("whatsapp", "+6281234567890");
47//! state.notify(&guest, &OrderShipped { order_id }).await?;
48//! let unread = user.unread_notifications(&db).await?;
49//! # let _ = unread; Ok(()) }
50//!
51//! // The app's own channel: `message` is what `to_channel` returned.
52//! # let _ =
53//! App::new().channel("whatsapp", |to: Recipient, message, state| async move {
54//!     let phone = to.address("whatsapp").or_else(|| to.user()?.get("phone"));
55//!     let _ = (state, phone, message); // call your provider's API here
56//!     Ok(())
57//! })
58//! # ;
59//! ```
60
61use 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/// Where a notification goes.
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78#[non_exhaustive]
79pub enum Channel {
80    /// Sent with `state.mailer` (`to_mail`).
81    Mail,
82    /// Stored in the `notifications` table for an in-app list
83    /// (`to_database`); only for users.
84    Database,
85    /// One of the app's own channels, registered with `App::channel`
86    /// (`to_channel`).
87    Custom(&'static str),
88}
89
90/// Who a notification goes to: a user, addresses for someone without an
91/// account, or a user with an extra address.
92#[derive(Debug, Clone, Default, Serialize, Deserialize)]
93#[non_exhaustive]
94pub struct Recipient {
95    user: Option<User>,
96    /// An address per channel, e.g. `mail` → `a@b.c`, `whatsapp` → `+62…`.
97    routes: BTreeMap<String, String>,
98    /// The language to write in; see [`Recipient::locale`].
99    #[serde(default)]
100    language: Option<String>,
101}
102
103impl Recipient {
104    /// The user, at their email address (and any addresses added with `and`).
105    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    /// The user, if the recipient has an account.
114    pub fn user(&self) -> Option<&User> {
115        self.user.as_ref()
116    }
117
118    /// Someone without an account: `Recipient::to("mail", "a@b.c")`.
119    pub fn to(channel: &str, address: impl Into<String>) -> Self {
120        Self::default().and(channel, address)
121    }
122
123    /// Adds (or replaces) the address for `channel`.
124    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    /// The address for `channel`; for `mail`, the user's email when no
130    /// other address was given.
131    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    /// Whether `address` is one of the recipient's addresses, on any channel.
139    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    /// The address for the `mail` channel (see [`Recipient::address`]).
144    pub fn email(&self) -> Option<String> {
145        self.address("mail")
146    }
147
148    /// Writes to this recipient in `locale` (e.g. `"es"`).
149    pub fn in_locale(mut self, locale: impl Into<String>) -> Self {
150        self.language = Some(locale.into());
151        self
152    }
153
154    /// The recipient's language: the one given with [`Recipient::in_locale`],
155    /// else the user's `locale` column if the `users` table has one.
156    /// Notifications build their messages in it (`t()` in mail views,
157    /// `state.current_lang()` in code).
158    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
186/// A message to a [`Recipient`], with a version for each channel it goes out on.
187pub trait Notification: Send + Sync {
188    /// Stored with database notifications, e.g. to pick an icon.
189    fn kind(&self) -> &'static str;
190
191    /// The channels to deliver on for this recipient (Laravel's `via`),
192    /// e.g. WhatsApp only for users who turned it on; only `Channel::Mail`
193    /// unless overridden.
194    fn channels(&self, to: &Recipient) -> Vec<Channel> {
195        let _ = to;
196        vec![Channel::Mail]
197    }
198
199    /// The mail for `Channel::Mail`; an error unless overridden.
200    fn to_mail(&self, _to: &Recipient, _state: &AppState) -> Result<Mail> {
201        Err(anyhow!("notification `{}` has no mail version", self.kind()).into())
202    }
203
204    /// The JSON stored for `Channel::Database` (`DatabaseNotification::data`);
205    /// `null` by default. Return a [`DatabaseMessage`] for the UI kit's
206    /// `notification_bell`. It runs in the recipient's language, like
207    /// `to_mail`.
208    fn to_database(&self, to: &Recipient, state: &AppState) -> Result<Value> {
209        let _ = (to, state);
210        Ok(Value::Null)
211    }
212
213    /// The message for one of the app's own channels; the channel's handler
214    /// gets it.
215    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/// What a notification stores for the in-app list, in the shape the UI
226/// kit's `notification_bell` shows (and pushes as a toast when it arrives):
227/// a status (its icon), a title, a line of text, a link and buttons. Return
228/// it from [`Notification::to_database`] with `.into()`; `with` adds the
229/// app's own keys next to them.
230#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
231#[non_exhaustive]
232pub struct DatabaseMessage {
233    /// Its icon and color: success, info, warning or error.
234    pub status: ToastKind,
235    /// The first line.
236    pub title: String,
237    /// A second, lighter line.
238    #[serde(default, skip_serializing_if = "Option::is_none")]
239    pub body: Option<String>,
240    /// Where opening it goes (it is marked read on the way).
241    #[serde(default, skip_serializing_if = "Option::is_none")]
242    pub url: Option<String>,
243    /// Links or buttons under the text.
244    #[serde(default, skip_serializing_if = "Vec::is_empty")]
245    pub actions: Vec<ToastAction>,
246    /// The app's own keys (`with`), stored next to the others.
247    #[serde(flatten)]
248    pub extra: serde_json::Map<String, Value>,
249}
250
251impl DatabaseMessage {
252    /// A message with `status` and `title`.
253    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    /// A success message (a green check).
265    pub fn success(title: impl Into<String>) -> Self {
266        Self::new(ToastKind::Success, title)
267    }
268
269    /// An info message.
270    pub fn info(title: impl Into<String>) -> Self {
271        Self::new(ToastKind::Info, title)
272    }
273
274    /// A warning.
275    pub fn warning(title: impl Into<String>) -> Self {
276        Self::new(ToastKind::Warning, title)
277    }
278
279    /// An error.
280    pub fn error(title: impl Into<String>) -> Self {
281        Self::new(ToastKind::Error, title)
282    }
283
284    /// Adds a second line.
285    pub fn body(mut self, body: impl Into<String>) -> Self {
286        self.body = Some(body.into());
287        self
288    }
289
290    /// Where opening the notification goes.
291    pub fn url(mut self, url: impl Into<String>) -> Self {
292        self.url = Some(url.into());
293        self
294    }
295
296    /// Adds a link or button.
297    pub fn action(mut self, action: ToastAction) -> Self {
298        self.actions.push(action);
299        self
300    }
301
302    /// Adds a link: `.link("Invoice", "/invoices/7")`.
303    pub fn link(self, label: impl Into<String>, url: impl Into<String>) -> Self {
304        self.action(ToastAction::link(label, url))
305    }
306
307    /// Stores `key` next to the message, for the app's own pages
308    /// (`notification.data.order_id`). The message's own keys win.
309    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/// A stored notification.
325#[derive(Debug, Clone, Serialize)]
326#[non_exhaustive]
327pub struct DatabaseNotification {
328    /// The `notifications` row id.
329    pub id: i64,
330    /// The notification's [`Notification::kind`].
331    pub kind: String,
332    /// What [`Notification::to_database`] returned.
333    pub data: Value,
334    /// When it was marked read; `None` while unread.
335    pub read_at: Option<DateTime>,
336    /// When it was stored.
337    pub created_at: DateTime,
338}
339
340impl DatabaseNotification {
341    /// The stored [`DatabaseMessage`], when `to_database` returned one (its
342    /// data has a `title`).
343    pub fn message(&self) -> Option<DatabaseMessage> {
344        serde_json::from_value(self.data.clone()).ok()
345    }
346}
347
348/// Wakes the open notification streams (`/notifications/stream`) of one
349/// user when something changed for them in this process; streams also look
350/// at the table every few seconds, for changes made by other servers or by
351/// `queue:work`. It also carries the app's own events
352/// ([`AppState::broadcast`]) to the streams open in this process.
353pub(crate) struct Hub {
354    tx: tokio::sync::broadcast::Sender<Signal>,
355}
356
357#[derive(Debug, Clone, PartialEq, Eq)]
358pub(crate) enum Signal {
359    /// Something changed for this user.
360    User(i64),
361    /// An app event for one user's streams, or (`None`) for every stream.
362    Event(Option<i64>, Arc<Broadcast>),
363    /// The server is shutting down.
364    Stop,
365}
366
367/// An app event on its way to the open pages: its DOM event name and its
368/// data, already JSON.
369#[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    /// Tells `user_id`'s streams to look now.
383    pub(crate) fn touch(&self, user_id: i64) {
384        let _ = self.tx.send(Signal::User(user_id));
385    }
386
387    /// Sends an app event to `user_id`'s streams, or to every stream.
388    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    /// Ends every stream, so a graceful shutdown doesn't wait for them.
393    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/// Delivers a message to one of the app's channels from the queue.
421#[derive(Serialize, Deserialize)]
422pub(crate) struct SendToChannel {
423    channel: String,
424    to: Recipient,
425    message: Value,
426    /// `App::channel_rate_limit` when this was queued.
427    #[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
445/// The channels a notification is delivered to, in delivery order: the
446/// database row first, so a failure there doesn't leave a sent message
447/// behind that a retry would send again; mail last.
448fn 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
458/// Whether `name` can be a DOM event name sent to pages: letters, digits
459/// and `-`, `_`, `:`, `.` (what `hx-trigger` and Alpine's `x-on` can name).
460fn 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    /// Sends the DOM event `event`, with `data` as its `detail`, to every
478    /// page open in this process with a notification stream (the UI kit's
479    /// `notification_bell` or `event_stream()`, which need
480    /// `Auth::new().notifications()`), whoever is logged in there.
481    ///
482    /// Pages listen as to any DOM event on `document`: htmx with
483    /// `hx-trigger="order-updated from:document"`, Alpine with
484    /// `x-on:order-updated.document="…"`, a script with
485    /// `document.addEventListener("order-updated", e => e.detail)`. The
486    /// event `renox:toast` with `{"toasts": [toast]}` shows toasts.
487    ///
488    /// It is fire-and-forget: nothing is stored, and pages that aren't
489    /// connected at that moment (closed, reconnecting, open on another
490    /// server, or a `queue:work` process sent it) never get it. Use a
491    /// database notification ([`AppState::notify`]) for what must arrive.
492    ///
493    /// ```
494    /// # use renox::prelude::*;
495    /// # fn demo(state: AppState, user: User) -> Result {
496    /// state.broadcast("order-updated", json!({ "id": 7, "status": "paid" }))?;
497    /// // Only Ana's pages (any tab, any device on this server):
498    /// state.broadcast_to(user.id, "renox:toast", json!({ "toasts": [Toast::info("Export ready")] }))?;
499    /// # Ok(()) }
500    /// ```
501    pub fn broadcast(&self, event: &str, data: impl Serialize) -> Result {
502        self.send_broadcast(None, event, data)
503    }
504
505    /// [`AppState::broadcast`] to the pages of one user (by id) only.
506    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        // Only users have an in-app list.
539        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    /// Delivers `notification` now to a user (`&user`) or to addresses (a
559    /// [`Recipient`]), on each of its channels. The database row is written
560    /// first and mail sent last, so a failure doesn't leave a message behind
561    /// that a retry would send again.
562    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    /// Like `notify`, but mail and the app's channels are sent by queue
591    /// workers, each channel as its own job with its own retries. The
592    /// messages are built now; the database row is written now.
593    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)?; // fail now for an unknown channel
609                    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    /// The user's notifications, newest first.
641    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    /// The user's notifications older than the one with id `before`,
654    /// newest first: the next page after a list ending at `before`.
655    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    /// One of the user's notifications, or `None` if it isn't theirs.
674    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    /// The user's unread notifications, newest first.
687    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    /// How many of the user's notifications are unread.
699    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    /// Marks one of the user's notifications read; returns whether it was theirs.
709    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    /// Marks one of the user's notifications unread again; returns whether
722    /// it was theirs.
723    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    /// Deletes one of the user's notifications; returns whether it was theirs.
734    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    /// Deletes all the user's notifications; returns how many there were.
744    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    /// Marks all the user's unread notifications read; returns how many there were.
754    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
766/// Deletes notifications read more than `age` ago; returns how many. Unread
767/// ones stay, however old. `rnx notifications:prune` (from the `Auth` module)
768/// runs it with `--days` (30 by default); schedule it, e.g. daily, since
769/// nothing else removes read notifications while their user exists.
770pub 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}