//! Notifications (hub spec §10): who to tell about an event, the inbox //! row, and email when the account asked for it and SMTP is configured. use crate::db::{self, accounts::Account, notify as ndb}; use crate::Shared; use std::collections::BTreeSet; /// An event worth telling people about. pub struct Event<'a> { pub kind: &'a str, pub title: String, pub url: String, pub actor: &'a Account, pub repo_id: i64, /// `issue` or `proposal` and its id, for thread subscribers. pub thread: Option<(&'a str, i64)>, /// Bodies to scan for `@mentions`. pub mention_text: &'a str, /// Accounts to tell whatever their subscriptions (author, assignees). pub direct: Vec, } /// `@username` tokens in a text, unique. pub fn mentions(text: &str) -> Vec { let re = regex::Regex::new(r"(?:^|[^\w/])@([A-Za-z0-9][A-Za-z0-9._-]{0,63})").unwrap(); let mut out = BTreeSet::new(); for c in re.captures_iter(text) { out.insert(c[1].trim_end_matches('.').to_string()); } out.into_iter().collect() } /// Deliver an event: subscribers of the thread, watchers of the /// repository, mentioned accounts and direct targets, never the actor. pub async fn deliver(app: &Shared, ev: Event<'_>) { let pool = &app.db; // Participants: the thread's subscribers, the mentioned, direct targets. // Watchers of the repository who are none of those are only watching. let mut participants: BTreeSet = BTreeSet::new(); if let Some((kind, id)) = ev.thread { if let Ok(subs) = ndb::subscribers(pool, kind, id).await { participants.extend(subs); } // Acting on a thread subscribes the actor to it. ndb::subscribe(pool, ev.actor.id, kind, id).await.ok(); } for name in mentions(ev.mention_text) { if let Ok(Some(a)) = db::accounts::account_by_name(pool, &name).await { participants.insert(a.id); } } participants.extend(ev.direct.iter().copied()); let mut targets: Vec<(i64, ndb::Reason)> = participants.iter().map(|id| (*id, ndb::Reason::Participating)).collect(); if let Ok(w) = ndb::watchers(pool, ev.repo_id).await { targets.extend(w.into_iter().filter(|id| !participants.contains(id)).map(|id| (id, ndb::Reason::Watching))); } targets.retain(|(id, _)| *id != ev.actor.id); let repo_id = (ev.repo_id > 0).then_some(ev.repo_id); for (id, reason) in targets { ndb::add( pool, ndb::New { account_id: id, repo_id, reason, kind: ev.kind, title: &ev.title, url: &ev.url, actor: &ev.actor.username }, ) .await .ok(); if let Ok(Some(a)) = db::accounts::account_by_id(pool, id).await { // Only to addresses the account has proven it reads (hub spec §5.1.1). if a.email_notifications && a.email_verified && !a.email.is_empty() && crate::mail::enabled(app) { email(app, &a, &ev.title, &ev.url, &ev.actor.username).await; } } } } async fn email(app: &Shared, to: &Account, title: &str, url: &str, actor: &str) { let unsubscribe = format!("{}/settings/notifications?unsubscribe={}", app.config.base_url(), to.unsubscribe_key); let body = format!("{actor}: {title}\n\n{}{url}\n\nStop these emails: {unsubscribe}\n", app.config.base_url()); if let Err(e) = crate::mail::send(app, to.name(), &to.email, title, &body).await { tracing::warn!("email to {}: {e}", to.email); } } #[cfg(test)] mod tests { use super::*; #[test] fn finds_mentions() { assert_eq!(mentions("cc @andy and @bob. not an email x@y.z, nor /@path"), vec!["andy", "bob"]); assert!(mentions("nothing here").is_empty()); } }