OXYGENHUB
◆ v0.9.20 oxygenhub / crates / hub / src / notify / mod.rs
7.3 KiB · Rust · last changed Phone alerts: a phone registers its Cloud Messaging token and key (PUT /api/v1/user/push), and each notification its account is told goes to it sealed to that key, sent keyless as the VM's service account; pins OxygenFlow main (refs oxygenhub-android#16) 8 days ago source blame history raw
1
//! Notifications (hub spec §10): who to tell about an event, the inbox
2
//! row, and email when the account asked for it and SMTP is configured.
3
4
use crate::db::{self, accounts::Account, notify as ndb};
5
use crate::Shared;
6
use std::collections::BTreeSet;
7
8
tokio::task_local! {
9
    /// The name of the agent-marked token this request came with, if any
10
    /// (oxygenhub#183): what an agent does with it is told to the token's
11
    /// owner too, though the owner is the actor.
12
    pub static AGENT: Option<String>;
13
}
14
15
/// The agent token acting now, when there is one.
16
pub fn agent_acting() -> Option<String> {
17
    AGENT.try_with(|a| a.clone()).ok().flatten()
18
}
19
20
/// An event worth telling people about.
21
pub struct Event<'a> {
22
    pub kind: &'a str,
23
    pub title: String,
24
    pub url: String,
25
    pub actor: &'a Account,
26
    pub repo_id: i64,
27
    /// `issue` or `proposal` and its id, for thread subscribers.
28
    pub thread: Option<(&'a str, i64)>,
29
    /// Bodies to scan for `@mentions`.
30
    pub mention_text: &'a str,
31
    /// Accounts to tell whatever their subscriptions (author, assignees).
32
    pub direct: Vec<i64>,
33
}
34
35
/// `@username` tokens in a text, unique.
36
pub fn mentions(text: &str) -> Vec<String> {
37
    let re = regex::Regex::new(r"(?:^|[^\w/])@([A-Za-z0-9][A-Za-z0-9._-]{0,63})").unwrap();
38
    let mut out = BTreeSet::new();
39
    for c in re.captures_iter(text) {
40
        out.insert(c[1].trim_end_matches('.').to_string());
41
    }
42
    out.into_iter().collect()
43
}
44
45
/// Deliver an event: subscribers of the thread, watchers of the
46
/// repository, mentioned accounts and direct targets, never the actor.
47
pub async fn deliver(app: &Shared, ev: Event<'_>) {
48
    let pool = &app.db;
49
    // Participants: the thread's subscribers, the mentioned, direct targets.
50
    // Watchers of the repository who are none of those are only watching.
51
    let mut participants: BTreeSet<i64> = BTreeSet::new();
52
    if let Some((kind, id)) = ev.thread {
53
        if let Ok(subs) = ndb::subscribers(pool, kind, id).await {
54
            participants.extend(subs);
55
        }
56
        // Acting on a thread subscribes the actor to it.
57
        ndb::subscribe(pool, ev.actor.id, kind, id).await.ok();
58
    }
59
    for name in mentions(ev.mention_text) {
60
        if let Ok(Some(a)) = db::accounts::account_by_name(pool, &name).await {
61
            participants.insert(a.id);
62
        }
63
    }
64
    participants.extend(ev.direct.iter().copied());
65
    let mut targets: Vec<(i64, ndb::Reason)> = participants.iter().map(|id| (*id, ndb::Reason::Participating)).collect();
66
    if let Ok(w) = ndb::watchers(pool, ev.repo_id).await {
67
        targets.extend(w.into_iter().filter(|id| !participants.contains(id)).map(|id| (id, ndb::Reason::Watching)));
68
    }
69
    // Never the actor, unless an agent acted with their token: then they
70
    // hear what their agent did.
71
    let agent = agent_acting();
72
    if agent.is_none() {
73
        targets.retain(|(id, _)| *id != ev.actor.id);
74
    }
75
    let actor = match &agent {
76
        Some(token) => format!("{} (agent token {token})", ev.actor.username),
77
        None => ev.actor.username.clone(),
78
    };
79
    tell(app, ev.kind, &ev.title, &ev.url, &actor, (ev.repo_id > 0).then_some(ev.repo_id), targets).await;
80
}
81
82
/// Tell each of `targets` about something: an inbox row, and an email
83
/// where the account asked for them and has proven its address.
84
pub async fn tell(app: &Shared, kind: &str, title: &str, url: &str, actor: &str, repo_id: Option<i64>, targets: Vec<(i64, ndb::Reason)>) {
85
    let pool = &app.db;
86
    for (id, reason) in targets {
87
        ndb::add(pool, ndb::New { account_id: id, repo_id, reason, kind, title, url, actor }).await.ok();
88
        app.bus.live(&crate::events::topic::user(id), "notification");
89
        // And to the account's phones, sealed (oxygenhub-android#16).
90
        let link = format!("{}{url}", app.config.base_url().trim_end_matches('/'));
91
        crate::push::send(app, id, crate::push::Alert { kind: kind.to_string(), title: subject(kind, title), url: link });
92
        if let Ok(Some(a)) = db::accounts::account_by_id(pool, id).await {
93
            // Only to addresses the account has proven it reads (hub spec §5.1.1).
94
            if a.email_notifications && a.email_verified && !a.email.is_empty() && crate::mail::enabled(app) {
95
                email(app, &a, kind, title, url, actor).await;
96
            }
97
        }
98
    }
99
}
100
101
/// What a kind of notification is called in an email's subject, with its
102
/// emoji, so a glance at the inbox says what happened (Andy, 2026-10-14).
103
pub fn label(kind: &str) -> Option<&'static str> {
104
    Some(match kind {
105
        "flow.failed" => "💥 Build Broken",
106
        "flow.fixed" => "🎉 Build Success",
107
        "flow.runner_drained" => "🛑 Runner Drained",
108
        "backup" => "⚠️ Backup Failed",
109
        "backup.recovered" => "✅ Backup Recovered",
110
        "backup.summary" => "📦 Daily Backup Summary",
111
        "proposal.opened" => "🔀 New Proposal",
112
        "proposal.review_requested" => "👀 Review Requested",
113
        "proposal.review" => "📝 New Review",
114
        "proposal.landed" => "🚀 Proposal Landed",
115
        "proposal.comment" | "issue.comment" | "drop.comment" => "💬 New Comment",
116
        "issue.opened" => "🐛 New Issue",
117
        "issue.assigned" => "📌 Issue Assigned",
118
        "issue.closed" => "✔️ Issue Closed",
119
        "account.registered" => "👋 New Sign-up",
120
        _ => return None,
121
    })
122
}
123
124
/// A notification's email subject: its label, then what happened.
125
pub fn subject(kind: &str, title: &str) -> String {
126
    match label(kind) {
127
        Some(l) => format!("{l}: {title}"),
128
        None => title.to_string(),
129
    }
130
}
131
132
async fn email(app: &Shared, to: &Account, kind: &str, title: &str, url: &str, actor: &str) {
133
    let unsubscribe = format!("{}/settings/notifications?unsubscribe={}", app.config.base_url(), to.unsubscribe_key);
134
    let link = format!("{}{url}", app.config.base_url());
135
    let body = format!("{actor}: {title}\n\n{link}\n\nStop these emails: {unsubscribe}\n");
136
    let action = crate::mail::Action { label: "Open it", url: &link };
137
    let subject = subject(kind, title);
138
    if let Err(e) = crate::mail::send_letter(app, to.name(), &to.email, &subject, &body, Some(action), Some(&unsubscribe)).await {
139
        tracing::warn!("email to {}: {e}", to.email);
140
        // Sent again from the work queue (#276), when mail is on at all.
141
        if crate::mail::enabled(app) {
142
            crate::queue::queue_mail(app, to.name(), &to.email, &subject, &body, Some(("Open it", &link)), Some(&unsubscribe)).await;
143
        }
144
    }
145
}
146
147
#[cfg(test)]
148
mod tests {
149
    use super::*;
150
151
    #[test]
152
    fn subjects_say_what_happened() {
153
        assert_eq!(
154
            subject("flow.failed", "andy/demo: run #4 on main failed (test)"),
155
            "💥 Build Broken: andy/demo: run #4 on main failed (test)"
156
        );
157
        assert_eq!(
158
            subject("flow.fixed", "andy/demo: run #5 on main passed: fixed"),
159
            "🎉 Build Success: andy/demo: run #5 on main passed: fixed"
160
        );
161
        assert_eq!(subject("backup.summary", "x"), "📦 Daily Backup Summary: x");
162
        assert_eq!(subject("something.new", "x"), "x", "a kind without a label keeps its title");
163
    }
164
165
    #[test]
166
    fn finds_mentions() {
167
        assert_eq!(mentions("cc @andy and @bob. not an email [email protected], nor /@path"), vec!["andy", "bob"]);
168
        assert!(mentions("nothing here").is_empty());
169
    }
170
}