Skip to main content

vector_core/
notify.rs

1//! Notification levels and mutes, for communities, channels and DMs alike.
2//!
3//! Two settings per scope, doing different jobs. **Level** decides what rings:
4//! every message, only your name, or nothing. **Mute** greys the row, drops its
5//! unread weight, and clamps the level to at most `Mentions` — a volume knob,
6//! not an off switch, which is why `Nothing` is not a synonym for it.
7//!
8//! Level resolves down the chain Community → Channel, most specific opinion
9//! winning. Mute unions down it: muting a community mutes every channel in it.
10//! With no opinion stored anywhere, what the conversation IS picks the level: a
11//! DM or a group chat rings for everything, a community only for your name.
12
13use std::collections::HashMap;
14use std::sync::{Arc, RwLock};
15
16/// What rings. Ordered loudest first, so the numeric rank orders "quieter".
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
18#[repr(u8)]
19pub enum NotifyLevel {
20    All = 0,
21    Mentions = 1,
22    Nothing = 2,
23}
24
25impl NotifyLevel {
26    pub fn as_u8(self) -> u8 {
27        self as u8
28    }
29
30    pub fn from_u8(v: u8) -> Option<Self> {
31        match v {
32            0 => Some(Self::All),
33            1 => Some(Self::Mentions),
34            2 => Some(Self::Nothing),
35            _ => None,
36        }
37    }
38
39    pub fn as_str(self) -> &'static str {
40        match self {
41            Self::All => "all",
42            Self::Mentions => "mentions",
43            Self::Nothing => "nothing",
44        }
45    }
46
47    pub fn from_label(s: &str) -> Option<Self> {
48        match s {
49            "all" => Some(Self::All),
50            "mentions" => Some(Self::Mentions),
51            "nothing" | "none" => Some(Self::Nothing),
52            _ => None,
53        }
54    }
55
56    /// The quieter of the two, which is how a mute clamps a level.
57    pub fn quieter_of(self, other: Self) -> Self {
58        if self >= other { self } else { other }
59    }
60}
61
62/// What a message is, loudest first. Resolved once at classification so a
63/// suppressed @everyone is `Normal` everywhere downstream: notification,
64/// ping badge and muted-row count alike.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum MessageClass {
67    Everyone,
68    Mention,
69    Normal,
70}
71
72/// Whether a message of this class rings at this level.
73pub fn passes(level: NotifyLevel, class: MessageClass) -> bool {
74    match level {
75        NotifyLevel::All => true,
76        NotifyLevel::Mentions => !matches!(class, MessageClass::Normal),
77        NotifyLevel::Nothing => false,
78    }
79}
80
81/// `mute_until` sentinel for a mute with no end.
82pub const MUTE_FOREVER: i64 = -1;
83/// `mute_until` sentinel for "not muted".
84pub const MUTE_OFF: i64 = 0;
85
86pub fn is_muted_at(mute_until: i64, now_ms: i64) -> bool {
87    mute_until == MUTE_FOREVER || mute_until > now_ms
88}
89
90pub fn now_ms() -> i64 {
91    crate::clock::now_ms() as i64
92}
93
94/// One scope's stored settings. `None` means inherit; `suppress_everyone` is
95/// only ever set at community scope.
96#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
97pub struct ScopePrefs {
98    pub level: Option<NotifyLevel>,
99    pub mute_until: i64,
100    pub suppress_everyone: Option<bool>,
101}
102
103impl ScopePrefs {
104    pub fn is_default(&self) -> bool {
105        self.level.is_none() && self.mute_until == MUTE_OFF && self.suppress_everyone.is_none()
106    }
107    pub fn muted_at(&self, now_ms: i64) -> bool {
108        is_muted_at(self.mute_until, now_ms)
109    }
110}
111
112/// A scope's settings after the chain has been walked.
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub struct Resolved {
115    /// The level in force before the mute clamp, which is what a menu ticks.
116    pub level: NotifyLevel,
117    pub muted: bool,
118    /// The level after the clamp, which is what actually rings and badges.
119    pub ring: NotifyLevel,
120}
121
122// ============================================================================
123// Per-account cache
124// ============================================================================
125
126#[derive(Default)]
127struct Store {
128    loaded: bool,
129    scopes: HashMap<String, ScopePrefs>,
130    /// Channel ids their community still lists. A tombstoned channel keeps its
131    /// chat row and its history, so "has a `community_id`" is not the same
132    /// question as "has a row you can open and clear".
133    live_channels: Option<std::collections::HashSet<[u8; 32]>>,
134    /// Concord groups that are communities rather than group chats: more than one
135    /// channel, or a live invite link anyone can join by.
136    communities: Option<std::collections::HashSet<[u8; 32]>>,
137}
138
139/// Whether `id` names a member of `set`, which holds ids decoded from canonical hex.
140fn holds(set: &std::collections::HashSet<[u8; 32]>, id: &str) -> bool {
141    crate::community::id32_from_hex(id).is_some_and(|b| set.contains(&b))
142}
143
144struct NotifyStore;
145
146fn store() -> Arc<RwLock<Store>> {
147    crate::db::current_session().scoped::<NotifyStore, _>()
148}
149
150/// Read the table into memory. Called once when a database is opened, because
151/// every badge recount resolves every chat and a lazy load would put a SQLite
152/// round trip on that path.
153///
154/// A failed read leaves the cache unloaded rather than latching an empty map,
155/// and [`is_loaded`] is what tells a writer not to act on the emptiness.
156pub fn warm() {
157    let cell = store();
158    if cell.read().map(|g| g.loaded).unwrap_or(false) {
159        return;
160    }
161    let rows = match crate::db::notify::load_all() {
162        Ok(rows) => rows,
163        Err(_) => return,
164    };
165    if let Ok(mut g) = cell.write() {
166        g.scopes = rows;
167        g.loaded = true;
168    };
169}
170
171/// Whether the table has actually been read. An unloaded cache answers
172/// "default" for every scope, which is indistinguishable from "nothing is
173/// stored" — so anything that WRITES state derived from it must check this
174/// first, the same rule `synced_prefs::is_hydrated` applies to publishing.
175pub fn is_loaded() -> bool {
176    store().read().map(|g| g.loaded).unwrap_or(false)
177}
178
179/// Drop the cache so the next warm re-reads the table.
180pub fn invalidate() {
181    if let Ok(mut g) = store().write() {
182        g.loaded = false;
183        g.scopes.clear();
184        g.live_channels = None;
185        g.communities = None;
186    }
187}
188
189/// Forget what was read off the communities: a channel set or an invite-link
190/// registry was rewritten, which can change both what is listed and whether a
191/// group is a group chat or a community.
192pub fn invalidate_communities() {
193    if let Ok(mut g) = store().write() {
194        g.live_channels = None;
195        g.communities = None;
196    }
197}
198
199/// Whether `community_id` is a community rather than a group chat. A group chat
200/// is one channel behind no invite link; anything bigger or open to strangers
201/// is a community, and a busy one can't ring for every message.
202pub fn is_community(community_id: &str) -> bool {
203    let cell = store();
204    if let Ok(g) = cell.read() {
205        if let Some(set) = g.communities.as_ref() {
206            return holds(set, community_id);
207        }
208    }
209    // Unknown keeps the louder default: a missed ping costs more than an extra one.
210    let ids = match crate::db::community::community_ids_beyond_group_chat() {
211        Ok(ids) => ids,
212        Err(_) => return false,
213    };
214    let found = holds(&ids, community_id);
215    if let Ok(mut g) = cell.write() {
216        g.communities = Some(ids);
217    }
218    found
219}
220
221/// The level a scope starts at when nothing on its chain says otherwise.
222/// `group_id` is the Concord group the scope belongs to (or is), if any.
223pub fn default_level(group_id: Option<&str>) -> NotifyLevel {
224    if group_id.is_some_and(is_community) { NotifyLevel::Mentions } else { NotifyLevel::All }
225}
226
227/// Whether `channel_id` is one its community still lists. A channel nobody
228/// lists has no row to open, so its unread can never be seen or cleared.
229pub fn channel_is_listed(channel_id: &str) -> bool {
230    let cell = store();
231    if let Ok(g) = cell.read() {
232        if let Some(set) = g.live_channels.as_ref() {
233            return holds(set, channel_id);
234        }
235    }
236    // Unknown beats silently dropping a room's unread.
237    let ids: std::collections::HashSet<[u8; 32]> = match crate::db::notify::live_channel_ids() {
238        Ok(ids) => ids.iter().filter_map(|id| crate::community::id32_from_hex(id)).collect(),
239        Err(_) => return true,
240    };
241    let listed = holds(&ids, channel_id);
242    if let Ok(mut g) = cell.write() {
243        g.live_channels = Some(ids);
244    }
245    listed
246}
247
248pub fn prefs(scope_id: &str) -> ScopePrefs {
249    store()
250        .read()
251        .ok()
252        .and_then(|g| g.scopes.get(scope_id).copied())
253        .unwrap_or_default()
254}
255
256pub fn all_prefs() -> HashMap<String, ScopePrefs> {
257    store().read().map(|g| g.scopes.clone()).unwrap_or_default()
258}
259
260/// Write a scope through to the database and the cache.
261pub fn set_prefs(scope_id: &str, next: ScopePrefs) -> Result<(), String> {
262    warm();
263    crate::db::notify::save(scope_id, &next)?;
264    if let Ok(mut g) = store().write() {
265        if next.is_default() {
266            g.scopes.remove(scope_id);
267        } else {
268            g.scopes.insert(scope_id.to_string(), next);
269        }
270    }
271    // A muted contact's pushes are held at the pusher: iOS can't drop one once it arrives.
272    crate::push::controls_changed();
273    Ok(())
274}
275
276pub fn set_level(scope_id: &str, level: Option<NotifyLevel>) -> Result<(), String> {
277    let mut next = prefs(scope_id);
278    next.level = level;
279    set_prefs(scope_id, next)
280}
281
282pub fn set_mute(scope_id: &str, mute_until: i64) -> Result<(), String> {
283    let mut next = prefs(scope_id);
284    next.mute_until = mute_until;
285    set_prefs(scope_id, next)
286}
287
288pub fn set_suppress_everyone(scope_id: &str, suppress: Option<bool>) -> Result<(), String> {
289    let mut next = prefs(scope_id);
290    next.suppress_everyone = suppress;
291    set_prefs(scope_id, next)
292}
293
294// ============================================================================
295// Resolution
296// ============================================================================
297
298/// Whether an authorized @everyone may ping, for a community. Two levers: the
299/// App Settings kill switch, which wins outright, and the community's own
300/// choice under it. A channel has no say, deliberately.
301///
302/// Separate from [`resolve`] because it reads a setting from the database and
303/// `resolve` runs once per chat on every badge recount.
304pub fn everyone_allowed(community_id: Option<&str>) -> bool {
305    let globally_muted = crate::db::settings::get_sql_setting("notif_mute_everyone".to_string())
306        .ok()
307        .flatten()
308        .is_some_and(|v| v == "true");
309    if globally_muted {
310        return false;
311    }
312    !community_id.is_some_and(|cid| prefs(cid).suppress_everyone.unwrap_or(false))
313}
314
315/// Walk the chain for one scope. `community_id` is the channel's community, or
316/// `None` for a DM or for a community resolving itself.
317pub fn resolve(scope_id: &str, community_id: Option<&str>, now_ms: i64) -> Resolved {
318    let own = prefs(scope_id);
319    let parent = community_id
320        .filter(|cid| *cid != scope_id)
321        .map(prefs)
322        .unwrap_or_default();
323    let fallback = default_level(Some(community_id.unwrap_or(scope_id)));
324    resolve_from(own, parent, fallback, now_ms)
325}
326
327/// The chain arithmetic on its own: level takes the most specific opinion,
328/// then `fallback`; mute takes either, and the mute clamps the level it hands back.
329pub fn resolve_from(own: ScopePrefs, parent: ScopePrefs, fallback: NotifyLevel, now_ms: i64) -> Resolved {
330    let level = own.level.or(parent.level).unwrap_or(fallback);
331    let muted = own.muted_at(now_ms) || parent.muted_at(now_ms);
332    let ring = level.quieter_of(if muted { NotifyLevel::Mentions } else { NotifyLevel::All });
333    Resolved { level, muted, ring }
334}
335
336/// The community a chat belongs to, or `None` for a DM.
337fn community_of(chat: &crate::chat::Chat) -> Option<&str> {
338    chat.metadata.community_id()
339}
340
341/// A chat's settings, with its stored `muted` flag folded in. That flag is the
342/// mirror this module keeps for the paths that predate it, and the landing
343/// point for a mute arriving over the older `vector/mutes` projection, so it
344/// counts as a mute in its own right rather than being assumed to agree.
345pub fn resolve_chat(chat: &crate::chat::Chat) -> Resolved {
346    let mut resolved = resolve(&chat.id, community_of(chat), now_ms());
347    if chat.muted && !resolved.muted {
348        resolved.muted = true;
349        resolved.ring = resolved.level.quieter_of(NotifyLevel::Mentions);
350    }
351    resolved
352}
353
354/// What a chat's row should badge with: full unread at `All`, pings at
355/// `Mentions`, nothing at `Nothing`.
356pub fn ring_for_chat(chat: &crate::chat::Chat) -> NotifyLevel {
357    resolve_chat(chat).ring
358}
359
360pub fn muted_for_chat(chat: &crate::chat::Chat) -> bool {
361    resolve_chat(chat).muted
362}
363
364/// Whether a chat's COMMUNITY is itself silenced, rather than this one room inside it.
365/// A surface that stands for the whole space must not grey because one channel is quiet.
366pub fn community_muted_for_chat(chat: &crate::chat::Chat) -> bool {
367    community_of(chat).is_some_and(|id| prefs(id).muted_at(now_ms()))
368}
369
370/// The predicate the older `vector/mutes` projection is both WRITTEN and READ
371/// with. Publishing one shape and applying another is how an inherited mute
372/// ratchets into a permanent per-channel one.
373///
374/// Chain-resolved, so a client that predates levels silences the same rooms
375/// this one does. Indefinite-only, because that list cannot carry a deadline:
376/// a timed mute in it comes back as a mute with no end, and the expiry that
377/// should have corrected it happens at boot, where publishing is not allowed.
378pub fn in_legacy_mute_list(own: ScopePrefs, parent: ScopePrefs, now_ms: i64) -> bool {
379    (own.muted_at(now_ms) || parent.muted_at(now_ms))
380        && (own.mute_until == MUTE_FOREVER || parent.mute_until == MUTE_FOREVER)
381}
382
383/// [`in_legacy_mute_list`] for a chat, stored flag folded in like [`resolve_chat`].
384pub fn legacy_muted_for_chat(chat: &crate::chat::Chat) -> bool {
385    let own = prefs(&chat.id);
386    let parent = community_of(chat)
387        .filter(|cid| *cid != chat.id)
388        .map(prefs)
389        .unwrap_or_default();
390    in_legacy_mute_list(own, parent, now_ms())
391        // A mute that only exists as the legacy mirror is indefinite by nature.
392        || (chat.muted && !own.muted_at(now_ms()) && !parent.muted_at(now_ms()))
393}
394
395/// Whether an @everyone in this chat still counts as someone calling your name.
396///
397/// Reads the community's own setting only, never the App Settings switch: this
398/// runs once per chat on every serialization, and that switch lives in the
399/// database. It has never affected badge counts anyway, only delivery.
400pub fn everyone_pings_for_chat(chat: &crate::chat::Chat) -> bool {
401    !community_of(chat)
402        .map(prefs)
403        .and_then(|p| p.suppress_everyone)
404        .unwrap_or(false)
405}
406
407// ============================================================================
408// Expiry
409// ============================================================================
410
411/// The soonest mute expiry still ahead of `now_ms`, for arming one timer
412/// rather than one per mute.
413pub fn next_expiry(now_ms: i64) -> Option<i64> {
414    store().read().ok().and_then(|g| {
415        g.scopes
416            .values()
417            .map(|p| p.mute_until)
418            .filter(|&u| u > now_ms)
419            .min()
420    })
421}
422
423/// Clear every mute whose timer has run out, returning the scopes that just
424/// lapsed. Expiry is a write rather than a read: the callers of `muted` read a
425/// cached boolean, and making them all consult the clock instead would be the
426/// wrong fix.
427pub fn sweep_expired(now_ms: i64) -> Vec<String> {
428    warm();
429    let cell = store();
430    let lapsed: Vec<String> = match cell.read() {
431        Ok(g) => g
432            .scopes
433            .iter()
434            .filter(|(_, p)| p.mute_until > MUTE_OFF && p.mute_until <= now_ms)
435            .map(|(id, _)| id.clone())
436            .collect(),
437        Err(_) => return Vec::new(),
438    };
439    if lapsed.is_empty() {
440        return lapsed;
441    }
442    if crate::db::notify::clear_expired_mutes(now_ms).is_err() {
443        return Vec::new();
444    }
445    if let Ok(mut g) = cell.write() {
446        for id in &lapsed {
447            let drop_row = match g.scopes.get_mut(id) {
448                Some(p) => {
449                    p.mute_until = MUTE_OFF;
450                    p.is_default()
451                }
452                None => false,
453            };
454            if drop_row {
455                g.scopes.remove(id);
456            }
457        }
458    }
459    lapsed
460}
461
462// ============================================================================
463// Cross-device projection
464// ============================================================================
465
466impl ScopePrefs {
467    pub fn to_wire(self) -> crate::synced_prefs::NotifyEntry {
468        crate::synced_prefs::NotifyEntry {
469            level: self.level.map(|l| l.as_str().to_string()),
470            mute_until: self.mute_until,
471            suppress_everyone: self.suppress_everyone,
472        }
473    }
474
475    pub fn from_wire(entry: &crate::synced_prefs::NotifyEntry) -> Self {
476        Self {
477            level: entry.level.as_deref().and_then(NotifyLevel::from_label),
478            mute_until: entry.mute_until,
479            suppress_everyone: entry.suppress_everyone,
480        }
481    }
482}
483
484/// This device's table as the publishable projection.
485pub fn to_wire() -> crate::synced_prefs::NotifyMap {
486    let mut map = crate::synced_prefs::NotifyMap::default();
487    for (scope_id, prefs) in all_prefs() {
488        let _ = map.set(&scope_id, prefs.to_wire());
489    }
490    map
491}
492
493/// Adopt a sibling device's list wholesale. Returns the scopes whose settings
494/// actually moved, so the caller only has to repaint those.
495pub fn apply_wire(map: &crate::synced_prefs::NotifyMap) -> Result<Vec<String>, String> {
496    // Adopting a list REPLACES the table, so an unloaded cache would compare the
497    // incoming set against an emptiness that only means "could not read" and
498    // report nothing moved.
499    warm();
500    if !is_loaded() {
501        return Err("notification preferences not read yet".to_string());
502    }
503    let next: HashMap<String, ScopePrefs> = map
504        .scopes
505        .iter()
506        .map(|(id, entry)| (id.clone(), ScopePrefs::from_wire(entry)))
507        .filter(|(_, p)| !p.is_default())
508        .collect();
509    let before = all_prefs();
510    crate::db::notify::replace_all(&next)?;
511    if let Ok(mut g) = store().write() {
512        g.scopes = next.clone();
513        g.loaded = true;
514    }
515    let mut moved: Vec<String> = next
516        .iter()
517        .filter(|(id, p)| before.get(*id) != Some(p))
518        .map(|(id, _)| id.clone())
519        .collect();
520    crate::push::controls_changed();
521    moved.extend(before.keys().filter(|id| !next.contains_key(*id)).cloned());
522    Ok(moved)
523}
524
525/// How much of a message a system notification reveals: the account's
526/// `notif_content_privacy` setting, read at notify time.
527#[derive(Debug, Clone, Copy, PartialEq, Eq)]
528pub enum ContentPrivacy {
529    /// Sender and message.
530    Full,
531    /// Who wrote, not what.
532    HideContent,
533    /// What was written, not who.
534    HideSender,
535    /// Only that something arrived.
536    HideAll,
537}
538
539impl ContentPrivacy {
540    /// What a notification may reveal right now: the account's setting, joined with
541    /// the streaming overlay while Streamer Mode is on.
542    pub fn load() -> Self {
543        Self::effective(Self::load_base(), &crate::synced_prefs::load_settings().streamer)
544    }
545
546    /// The account's own setting, without the streaming overlay.
547    pub fn load_base() -> Self {
548        Self::parse(crate::db::get_sql_setting("notif_content_privacy".to_string()).ok().flatten().as_deref())
549    }
550
551    /// Joined before applying: applying two levels in turn does not hide what their union does.
552    pub fn effective(base: Self, streamer: &crate::synced_prefs::StreamerSettings) -> Self {
553        if streamer.on {
554            base.join(Self::parse(Some(&streamer.notif)))
555        } else {
556            base
557        }
558    }
559
560    /// Hides whatever either one hides.
561    pub fn join(self, other: Self) -> Self {
562        Self::from_bits(self.bits() | other.bits())
563    }
564
565    fn bits(self) -> u8 {
566        match self {
567            Self::Full => 0b00,
568            Self::HideContent => 0b01,
569            Self::HideSender => 0b10,
570            Self::HideAll => 0b11,
571        }
572    }
573
574    fn from_bits(bits: u8) -> Self {
575        match bits & 0b11 {
576            0b00 => Self::Full,
577            0b01 => Self::HideContent,
578            0b10 => Self::HideSender,
579            _ => Self::HideAll,
580        }
581    }
582
583    /// The stored spelling, which the web service worker also reads.
584    pub fn as_str(self) -> &'static str {
585        match self {
586            Self::Full => "full",
587            Self::HideContent => "hide_content",
588            Self::HideSender => "hide_sender",
589            Self::HideAll => "hide_all",
590        }
591    }
592
593    fn parse(value: Option<&str>) -> Self {
594        match value {
595            Some("hide_content") => Self::HideContent,
596            Some("hide_sender") => Self::HideSender,
597            Some("hide_all") => Self::HideAll,
598            _ => Self::Full,
599        }
600    }
601}
602
603/// Stands in for every name Streamer Mode hides. Fixed length, so it says nothing about the name.
604pub const STREAM_MASK: &str = "•••••";
605
606/// Who Streamer Mode hides. Read once per notification, outside any state lock.
607#[derive(Debug, Clone, Default)]
608pub struct StreamGate {
609    on: bool,
610    me: Option<String>,
611}
612
613impl StreamGate {
614    pub fn load() -> Self {
615        if !crate::synced_prefs::load_settings().streamer.on {
616            return Self::default();
617        }
618        // The background service on Android binds an account without an identity.
619        let me = crate::state::my_public_key()
620            .and_then(|pk| nostr_sdk::prelude::ToBech32::to_bech32(&pk).ok())
621            .or_else(|| crate::db::get_current_account().ok());
622        Self { on: true, me }
623    }
624
625    pub fn new(on: bool, me: Option<String>) -> Self {
626        Self { on, me }
627    }
628
629    pub fn is_on(&self) -> bool {
630        self.on
631    }
632
633    /// Everyone but the active account is hidden unless they opted in. Someone not
634    /// fetched yet cannot have, so they are hidden too.
635    pub fn hides(&self, npub: &str, profile: Option<&crate::profile::Profile>) -> bool {
636        if !self.on || self.me.as_deref() == Some(npub) {
637            return false;
638        }
639        !profile.is_some_and(|p| p.flags.is_mine() || p.flags.is_stream_consent())
640    }
641}
642
643/// The name and avatar a notification shows for someone.
644#[derive(Debug, Clone, PartialEq, Eq)]
645pub struct Sender {
646    pub name: String,
647    pub avatar: Option<String>,
648}
649
650/// Nickname, then name, then display name, else `fallback`; masked with no avatar
651/// when the gate hides them. Every platform's notification names a sender through this.
652pub fn sender(state: &crate::state::ChatState, gate: &StreamGate, npub: &str, fallback: &str) -> Sender {
653    let profile = state.get_profile(npub);
654    if gate.hides(npub, profile) {
655        return Sender { name: STREAM_MASK.to_string(), avatar: None };
656    }
657    let Some(p) = profile else {
658        return Sender { name: fallback.to_string(), avatar: None };
659    };
660    Sender {
661        name: display_name(p).unwrap_or(fallback).to_string(),
662        avatar: p.has_avatar_cached().then(|| p.avatar_cached().into_owned()),
663    }
664}
665
666/// [`sender`] inside a community: the `nickname` they go by there, unless you named them yourself.
667pub fn sender_in(state: &crate::state::ChatState, gate: &StreamGate, npub: &str, fallback: &str, nickname: Option<String>) -> Sender {
668    let shown = sender(state, gate, npub, fallback);
669    let profile = state.get_profile(npub);
670    match nickname {
671        Some(name) if !gate.hides(npub, profile) && profile.is_none_or(|p| p.nickname().is_empty()) => Sender { name, ..shown },
672        _ => shown,
673    }
674}
675
676fn display_name(p: &crate::profile::Profile) -> Option<&str> {
677    [p.nickname(), p.name(), p.display_name()].into_iter().find(|n| !n.is_empty())
678}
679
680/// `content` without terminal escape sequences: an ```ansi block's colour codes are
681/// styling, and a notification has no way to show them.
682pub fn strip_ansi(content: &str) -> std::borrow::Cow<'_, str> {
683    if !content.contains('\x1b') {
684        return std::borrow::Cow::Borrowed(content);
685    }
686    let mut out = String::with_capacity(content.len());
687    let mut chars = content.chars().peekable();
688    while let Some(c) = chars.next() {
689        if c != '\x1b' {
690            out.push(c);
691            continue;
692        }
693        match chars.peek() {
694            // CSI: parameter and intermediate bytes, ended by one final byte.
695            Some('[') => {
696                chars.next();
697                while let Some(&n) = chars.peek() {
698                    if !('\x20'..='\x3f').contains(&n) {
699                        if ('\x40'..='\x7e').contains(&n) {
700                            chars.next();
701                        }
702                        break;
703                    }
704                    chars.next();
705                }
706            }
707            Some(n) if ('\x40'..='\x5f').contains(n) => {
708                chars.next();
709            }
710            _ => {}
711        }
712    }
713    std::borrow::Cow::Owned(out)
714}
715
716/// `content` with each mention (`@npub1…`, `nostr:npub1…`, a bare npub, or the same
717/// forms of an nprofile) read as `@name`. An unknown npub stays as written, except while streaming, where it and
718/// anyone hidden read as `@•••••`.
719pub fn resolve_mentions(content: &str, state: &crate::state::ChatState, gate: &StreamGate) -> String {
720    scan_mentions(content, |npub| {
721        let profile = state.get_profile(npub);
722        if gate.hides(npub, profile) {
723            return Some(STREAM_MASK.to_string());
724        }
725        profile.and_then(display_name).map(str::to_string)
726    })
727}
728
729/// The scanner behind [`resolve_mentions`]. `lookup` names a bare npub, or `None`
730/// to leave its token as written. An nprofile is looked up by the npub it encodes.
731///
732/// Anchors on byte offsets only inside the entity, which is always ASCII, so the
733/// text around it (emoji included) is copied whole.
734pub fn scan_mentions<F: Fn(&str) -> Option<String>>(content: &str, lookup: F) -> String {
735    const NPUB_LEN: usize = 63;
736    const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
737
738    let bytes = content.as_bytes();
739    let len = bytes.len();
740    let mut result = String::with_capacity(len);
741    let mut cursor = 0;
742
743    let mut i = 0;
744    while i + NPUB_LEN <= len {
745        if bytes[i..].starts_with(b"nprofile1") {
746            let end = i + 9 + bytes[i + 9..].iter().take_while(|b| BECH32.contains(&b.to_ascii_lowercase())).count();
747            let npub = <nostr_sdk::prelude::Nip19Profile as nostr_sdk::prelude::FromBech32>::from_bech32(&content[i..end])
748                .ok()
749                .and_then(|p| nostr_sdk::prelude::ToBech32::to_bech32(&p.public_key).ok());
750            if let Some(name) = npub.as_deref().and_then(&lookup) {
751                let mstart = mention_start(bytes, i);
752                result.push_str(&content[cursor..mstart]);
753                result.push('@');
754                result.push_str(&name);
755                cursor = end;
756            }
757            i = end;
758            continue;
759        }
760        let is_npub = &bytes[i..i + 5] == b"npub1"
761            && bytes[i + 5..i + NPUB_LEN]
762                .iter()
763                .all(|b| BECH32.contains(&b.to_ascii_lowercase()));
764        if is_npub {
765            let npub_end = i + NPUB_LEN;
766            if let Some(name) = lookup(&content[i..npub_end]) {
767                let mstart = mention_start(bytes, i);
768                result.push_str(&content[cursor..mstart]);
769                result.push('@');
770                result.push_str(&name);
771                cursor = npub_end;
772            }
773            i = npub_end;
774            continue;
775        }
776        i += 1;
777    }
778
779    result.push_str(&content[cursor..]);
780    result
781}
782
783/// Where the mention token at `i` starts: its `@` or `nostr:` prefix is swallowed, so the
784/// whole token collapses to one @name.
785fn mention_start(bytes: &[u8], i: usize) -> usize {
786    if i >= 1 && bytes[i - 1] == b'@' {
787        i - 1
788    } else if i >= 6 && &bytes[i - 6..i] == b"nostr:" {
789        i - 6
790    } else {
791        i
792    }
793}
794
795/// What a notification shows. Every platform passes its notification through
796/// [`Preview::apply`], so the setting means the same thing everywhere.
797#[derive(Debug, Clone, Default, PartialEq)]
798pub struct Preview {
799    pub title: String,
800    pub body: String,
801    pub sender: Option<String>,
802    pub avatar: Option<String>,
803    /// Where a community message was posted; None in a DM.
804    pub group: Option<String>,
805    pub group_avatar: Option<String>,
806}
807
808impl Preview {
809    /// Rewrite what is shown. Idempotent: a notification may pass through twice.
810    pub fn apply(&mut self, privacy: ContentPrivacy) {
811        match privacy {
812            ContentPrivacy::Full => {}
813            ContentPrivacy::HideContent => {
814                self.body = if self.group.is_some() { "Sent a message" } else { "Sent you a message" }.to_string();
815            }
816            ContentPrivacy::HideSender => {
817                self.title = self.group.clone().unwrap_or_else(|| "New message".to_string());
818                self.sender = None;
819                self.avatar = None;
820            }
821            ContentPrivacy::HideAll => {
822                *self = Preview {
823                    title: "Vector".to_string(),
824                    body: "You received a message".to_string(),
825                    ..Default::default()
826                };
827            }
828        }
829    }
830}
831
832#[cfg(test)]
833mod tests {
834    use super::*;
835
836    #[test]
837    fn strip_ansi_drops_escape_sequences() {
838        assert_eq!(strip_ansi("plain"), "plain");
839        assert_eq!(strip_ansi("\x1b[2;31mred\x1b[0m and \x1b[38;2;88;101;242mblurple\x1b[0m"), "red and blurple");
840        assert_eq!(strip_ansi("a\x1b[1;4mb\x1b[mc"), "abc");
841        assert_eq!(strip_ansi("lone \x1b and \x1bM up, cut \x1b[31"), "lone  and  up, cut ");
842        assert_eq!(strip_ansi("\x1b[31m\u{1F600}\x1b[\u{e9}"), "\u{1F600}\u{e9}");
843    }
844
845    fn dm() -> Preview {
846        Preview {
847            title: "Alice".into(),
848            body: "see you at 8".into(),
849            sender: Some("Alice".into()),
850            avatar: Some("/a.png".into()),
851            ..Default::default()
852        }
853    }
854
855    fn channel() -> Preview {
856        Preview {
857            title: "Alice - Rust Club".into(),
858            body: "see you at 8".into(),
859            sender: Some("Alice".into()),
860            avatar: Some("/a.png".into()),
861            group: Some("Rust Club".into()),
862            group_avatar: Some("/club.png".into()),
863        }
864    }
865
866    #[test]
867    fn content_privacy_reads_every_stored_value() {
868        assert_eq!(ContentPrivacy::parse(None), ContentPrivacy::Full);
869        assert_eq!(ContentPrivacy::parse(Some("full")), ContentPrivacy::Full);
870        assert_eq!(ContentPrivacy::parse(Some("hide_content")), ContentPrivacy::HideContent);
871        assert_eq!(ContentPrivacy::parse(Some("hide_sender")), ContentPrivacy::HideSender);
872        assert_eq!(ContentPrivacy::parse(Some("hide_all")), ContentPrivacy::HideAll);
873        assert_eq!(ContentPrivacy::parse(Some("true")), ContentPrivacy::Full);
874    }
875
876    #[test]
877    fn hiding_the_sender_keeps_the_message_and_the_community() {
878        let mut p = dm();
879        p.apply(ContentPrivacy::HideSender);
880        assert_eq!((p.title.as_str(), p.body.as_str()), ("New message", "see you at 8"));
881        assert_eq!((p.sender, p.avatar), (None, None));
882
883        let mut p = channel();
884        p.apply(ContentPrivacy::HideSender);
885        assert_eq!((p.title.as_str(), p.body.as_str()), ("Rust Club", "see you at 8"));
886        assert_eq!((p.sender, p.avatar), (None, None));
887        assert_eq!(p.group_avatar.as_deref(), Some("/club.png"));
888    }
889
890    #[test]
891    fn hiding_the_message_keeps_the_sender() {
892        let mut p = dm();
893        p.apply(ContentPrivacy::HideContent);
894        assert_eq!((p.title.as_str(), p.body.as_str()), ("Alice", "Sent you a message"));
895        assert_eq!(p.avatar.as_deref(), Some("/a.png"));
896
897        let mut p = channel();
898        p.apply(ContentPrivacy::HideContent);
899        assert_eq!(p.body, "Sent a message");
900        assert_eq!(p.sender.as_deref(), Some("Alice"));
901    }
902
903    #[test]
904    fn hiding_everything_leaves_nothing_identifying() {
905        for mut p in [dm(), channel()] {
906            p.apply(ContentPrivacy::HideAll);
907            assert_eq!(p, Preview { title: "Vector".into(), body: "You received a message".into(), ..Default::default() });
908        }
909    }
910
911    #[test]
912    fn content_privacy_is_idempotent() {
913        for privacy in [ContentPrivacy::Full, ContentPrivacy::HideContent, ContentPrivacy::HideSender, ContentPrivacy::HideAll] {
914            for base in [dm(), channel()] {
915                let mut once = base.clone();
916                once.apply(privacy);
917                let mut twice = once.clone();
918                twice.apply(privacy);
919                assert_eq!(once, twice, "{privacy:?}");
920            }
921        }
922    }
923
924    const ALL_PRIVACY: [ContentPrivacy; 4] =
925        [ContentPrivacy::Full, ContentPrivacy::HideContent, ContentPrivacy::HideSender, ContentPrivacy::HideAll];
926
927    #[test]
928    fn privacy_joins_as_a_two_bit_union() {
929        for x in ALL_PRIVACY {
930            assert_eq!(ContentPrivacy::Full.join(x), x, "Full adds nothing to {x:?}");
931            assert_eq!(x.join(ContentPrivacy::Full), x);
932            assert_eq!(x.join(x), x, "joining {x:?} with itself is idempotent");
933            assert_eq!(x.join(ContentPrivacy::HideAll), ContentPrivacy::HideAll);
934            for y in ALL_PRIVACY {
935                assert_eq!(x.join(y), y.join(x), "{x:?} with {y:?} commutes");
936            }
937        }
938        assert_eq!(ContentPrivacy::HideContent.join(ContentPrivacy::HideSender), ContentPrivacy::HideAll);
939    }
940
941    #[test]
942    fn joining_first_hides_more_than_applying_twice() {
943        let mut twice = channel();
944        twice.apply(ContentPrivacy::HideSender);
945        twice.apply(ContentPrivacy::HideContent);
946        let mut joined = channel();
947        joined.apply(ContentPrivacy::HideSender.join(ContentPrivacy::HideContent));
948        assert_ne!(twice, joined, "applying in turn leaves the community showing");
949        assert_eq!(joined.group, None);
950    }
951
952    #[test]
953    fn privacy_spelling_round_trips() {
954        for x in ALL_PRIVACY {
955            assert_eq!(ContentPrivacy::parse(Some(x.as_str())), x);
956        }
957        assert_eq!(ContentPrivacy::parse(Some("none")), ContentPrivacy::Full, "the overlay's off spelling");
958    }
959
960    fn streaming(on: bool, notif: &str) -> crate::synced_prefs::StreamerSettings {
961        crate::synced_prefs::StreamerSettings { on, notif: notif.into(), ..Default::default() }
962    }
963
964    #[test]
965    fn the_overlay_counts_only_while_live() {
966        let base = ContentPrivacy::HideContent;
967        assert_eq!(ContentPrivacy::effective(base, &streaming(false, "hide_sender")), base);
968        assert_eq!(ContentPrivacy::effective(base, &streaming(true, "hide_sender")), ContentPrivacy::HideAll);
969        assert_eq!(ContentPrivacy::effective(base, &streaming(true, "none")), base);
970        assert_eq!(
971            ContentPrivacy::effective(ContentPrivacy::Full, &streaming(true, "hide_content")),
972            ContentPrivacy::HideContent
973        );
974    }
975
976    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
977        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
978        crate::db::close_database();
979        crate::db::clear_id_caches();
980        use nostr_sdk::prelude::ToBech32;
981        let tmp = tempfile::tempdir().unwrap();
982        let account = nostr_sdk::prelude::Keys::generate().public_key().to_bech32().unwrap();
983        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
984        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
985        crate::db::set_current_account(account.clone()).unwrap();
986        crate::db::init_database(&account).unwrap();
987        (tmp, guard)
988    }
989
990    #[test]
991    fn load_reads_the_setting_and_the_overlay() {
992        let (_tmp, _guard) = init_test_db();
993        use crate::synced_prefs::{save_local_raw, Pref, SyncedSettings};
994        crate::db::set_sql_setting("notif_content_privacy".into(), "hide_content".into()).unwrap();
995        let mut settings = SyncedSettings::default();
996        settings.streamer = streaming(true, "hide_sender");
997        save_local_raw(Pref::Settings, &settings.to_json()).unwrap();
998        assert_eq!(ContentPrivacy::load_base(), ContentPrivacy::HideContent);
999        assert_eq!(ContentPrivacy::load(), ContentPrivacy::HideAll);
1000
1001        settings.streamer.on = false;
1002        save_local_raw(Pref::Settings, &settings.to_json()).unwrap();
1003        assert_eq!(ContentPrivacy::load(), ContentPrivacy::HideContent, "off, the overlay is ignored");
1004    }
1005
1006    const ME: &str = "npub1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq";
1007    const FAN: &str = "npub1pppppppppppppppppppppppppppppppppppppppppppppppppppppppppp";
1008    const SHY: &str = "npub1zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
1009    const STRANGER: &str = "npub1rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr";
1010
1011    fn people() -> crate::state::ChatState {
1012        let mut state = crate::state::ChatState::new();
1013        let person = |name: &str, consent: bool| {
1014            let mut p = crate::profile::Profile::new();
1015            p.set_name(name);
1016            p.set_avatar_cached(&format!("/{name}.png"));
1017            p.flags.set_stream_consent(consent);
1018            p
1019        };
1020        state.insert_or_replace_profile(ME, person("Me", false));
1021        let mut fan = person("Fan", true);
1022        fan.set_nickname("Bestie");
1023        state.insert_or_replace_profile(FAN, fan);
1024        state.insert_or_replace_profile(SHY, person("Shy", false));
1025        state
1026    }
1027
1028    #[test]
1029    fn streaming_masks_everyone_but_me_and_those_who_opted_in() {
1030        let state = people();
1031        let live = StreamGate::new(true, Some(ME.into()));
1032        let shown = |npub| sender(&state, &live, npub, "New Message");
1033
1034        assert_eq!(shown(ME), Sender { name: "Me".into(), avatar: Some("/Me.png".into()) });
1035        assert_eq!(shown(FAN), Sender { name: "Bestie".into(), avatar: Some("/Fan.png".into()) }, "opted in reads as normal, nickname too");
1036        for hidden in [SHY, STRANGER] {
1037            assert_eq!(shown(hidden), Sender { name: STREAM_MASK.into(), avatar: None }, "{hidden}");
1038        }
1039        assert_eq!(STREAM_MASK.chars().count(), 5);
1040
1041        let off = StreamGate::default();
1042        assert_eq!(sender(&state, &off, SHY, "New Message").name, "Shy");
1043        assert_eq!(sender(&state, &off, STRANGER, "New Message"), Sender { name: "New Message".into(), avatar: None });
1044    }
1045
1046    #[test]
1047    fn my_own_profile_shows_even_without_an_identity() {
1048        let mut state = people();
1049        state.get_profile_mut(SHY).unwrap().flags.set_mine(true);
1050        let live = StreamGate::new(true, None);
1051        assert_eq!(sender(&state, &live, SHY, "x").name, "Shy");
1052        assert_eq!(sender(&state, &live, ME, "x").name, STREAM_MASK, "another local account is hidden");
1053    }
1054
1055    #[test]
1056    fn mentions_are_masked_while_live_and_named_otherwise() {
1057        let state = people();
1058        let text = format!("@{SHY} meet nostr:{FAN} and {STRANGER}, from @{ME}");
1059        let live = StreamGate::new(true, Some(ME.into()));
1060        assert_eq!(resolve_mentions(&text, &state, &live), "@••••• meet @Bestie and @•••••, from @Me");
1061
1062        let off = StreamGate::default();
1063        assert_eq!(
1064            resolve_mentions(&text, &state, &off),
1065            format!("@Shy meet @Bestie and {STRANGER}, from @Me"),
1066            "an unknown npub stays as written when not live"
1067        );
1068    }
1069
1070    #[test]
1071    fn an_nprofile_mention_reads_as_the_npub_it_encodes() {
1072        use nostr_sdk::prelude::{Keys, Nip19Profile, RelayUrl, ToBech32};
1073        let mut state = people();
1074        let pk = Keys::generate().public_key();
1075        let npub = pk.to_bech32().unwrap();
1076        let mut p = crate::profile::Profile::new();
1077        p.set_name("Hidden");
1078        state.insert_or_replace_profile(&npub, p);
1079        let relay = RelayUrl::parse("wss://relay.example.com").unwrap();
1080        let nprofile = Nip19Profile::new(pk, [relay]).to_bech32().unwrap();
1081
1082        let live = StreamGate::new(true, Some(ME.into()));
1083        assert_eq!(resolve_mentions(&format!("ask nostr:{nprofile} now"), &state, &live), "ask @••••• now");
1084        assert_eq!(resolve_mentions(&format!("ask @{nprofile}"), &state, &StreamGate::default()), "ask @Hidden");
1085        let stranger = Nip19Profile::new(Keys::generate().public_key(), []).to_bech32().unwrap();
1086        assert_eq!(resolve_mentions(&format!("hi {stranger}"), &state, &live), "hi @•••••", "unknown is hidden too");
1087        assert_eq!(scan_mentions("nprofile1qqqq broken", |_| Some("x".into())), "nprofile1qqqq broken");
1088    }
1089
1090    #[test]
1091    fn mention_scanner_reads_every_form() {
1092        let npub = format!("npub1{}", "q".repeat(58));
1093        let unknown = format!("npub1{}", "p".repeat(58));
1094        let known: &str = &npub;
1095        let lookup = |n: &str| (n == known).then(|| "Alice".to_string());
1096
1097        assert_eq!(scan_mentions(&format!("hey @{npub}!"), lookup), "hey @Alice!");
1098        assert_eq!(scan_mentions(&format!("hey nostr:{npub}!"), lookup), "hey @Alice!");
1099        assert_eq!(scan_mentions(&format!("hey {npub}!"), lookup), "hey @Alice!");
1100        assert_eq!(scan_mentions(&format!("hi nostr:{unknown}"), lookup), format!("hi nostr:{unknown}"));
1101        assert_eq!(scan_mentions(&format!("{npub} and nostr:{npub} done"), lookup), "@Alice and @Alice done");
1102        assert_eq!(scan_mentions("just a normal line 🎉", lookup), "just a normal line 🎉");
1103    }
1104
1105    #[test]
1106    fn mute_clamps_the_level_to_mentions() {
1107        assert_eq!(NotifyLevel::All.quieter_of(NotifyLevel::Mentions), NotifyLevel::Mentions);
1108        // Nothing is already quieter than the clamp, so a mute cannot make it louder.
1109        assert_eq!(NotifyLevel::Nothing.quieter_of(NotifyLevel::Mentions), NotifyLevel::Nothing);
1110        assert_eq!(NotifyLevel::Mentions.quieter_of(NotifyLevel::All), NotifyLevel::Mentions);
1111    }
1112
1113    #[test]
1114    fn level_decides_which_classes_ring() {
1115        for class in [MessageClass::Everyone, MessageClass::Mention, MessageClass::Normal] {
1116            assert!(passes(NotifyLevel::All, class));
1117            assert!(!passes(NotifyLevel::Nothing, class));
1118        }
1119        assert!(passes(NotifyLevel::Mentions, MessageClass::Mention));
1120        assert!(passes(NotifyLevel::Mentions, MessageClass::Everyone));
1121        assert!(!passes(NotifyLevel::Mentions, MessageClass::Normal));
1122    }
1123
1124    #[test]
1125    fn mute_sentinels() {
1126        assert!(is_muted_at(MUTE_FOREVER, 10_000));
1127        assert!(!is_muted_at(MUTE_OFF, 10_000));
1128        assert!(is_muted_at(10_001, 10_000));
1129        assert!(!is_muted_at(10_000, 10_000), "an expiry that has arrived is over");
1130    }
1131
1132    #[test]
1133    fn a_scope_at_every_default_stores_nothing() {
1134        assert!(ScopePrefs::default().is_default());
1135        assert!(!ScopePrefs { mute_until: MUTE_FOREVER, ..Default::default() }.is_default());
1136        assert!(!ScopePrefs { level: Some(NotifyLevel::Nothing), ..Default::default() }.is_default());
1137    }
1138
1139    fn at(level: Option<NotifyLevel>, mute_until: i64) -> ScopePrefs {
1140        ScopePrefs { level, mute_until, suppress_everyone: None }
1141    }
1142
1143    #[test]
1144    fn a_channel_opinion_beats_its_community() {
1145        let r = resolve_from(at(Some(NotifyLevel::All), 0), at(Some(NotifyLevel::Nothing), 0), NotifyLevel::All, 0);
1146        assert_eq!(r.level, NotifyLevel::All);
1147        assert_eq!(r.ring, NotifyLevel::All);
1148    }
1149
1150    #[test]
1151    fn a_channel_with_no_opinion_takes_its_community() {
1152        let r = resolve_from(at(None, 0), at(Some(NotifyLevel::Mentions), 0), NotifyLevel::All, 0);
1153        assert_eq!(r.level, NotifyLevel::Mentions);
1154    }
1155
1156    #[test]
1157    fn nothing_stored_anywhere_takes_what_the_conversation_is() {
1158        let chat = resolve_from(ScopePrefs::default(), ScopePrefs::default(), NotifyLevel::All, 0);
1159        assert_eq!(chat.level, NotifyLevel::All);
1160        assert!(!chat.muted);
1161        let community = resolve_from(ScopePrefs::default(), ScopePrefs::default(), NotifyLevel::Mentions, 0);
1162        assert_eq!(community.ring, NotifyLevel::Mentions);
1163    }
1164
1165    #[test]
1166    fn any_stored_opinion_beats_the_default() {
1167        let own = resolve_from(at(Some(NotifyLevel::All), 0), ScopePrefs::default(), NotifyLevel::Mentions, 0);
1168        assert_eq!(own.level, NotifyLevel::All);
1169        let inherited = resolve_from(ScopePrefs::default(), at(Some(NotifyLevel::All), 0), NotifyLevel::Mentions, 0);
1170        assert_eq!(inherited.level, NotifyLevel::All, "a community set to All keeps its channels loud");
1171    }
1172
1173    #[test]
1174    fn a_community_mute_reaches_a_channel_that_set_none_itself() {
1175        // Mute unions downward, unlike level: the channel cannot opt out of it.
1176        let r = resolve_from(at(Some(NotifyLevel::All), MUTE_OFF), at(None, MUTE_FOREVER), NotifyLevel::All, 0);
1177        assert!(r.muted);
1178        assert_eq!(r.level, NotifyLevel::All, "the level underneath is untouched");
1179        assert_eq!(r.ring, NotifyLevel::Mentions, "but the mute clamps what rings");
1180    }
1181
1182    #[test]
1183    fn a_mute_never_makes_a_quiet_channel_louder() {
1184        let r = resolve_from(at(Some(NotifyLevel::Nothing), MUTE_FOREVER), ScopePrefs::default(), NotifyLevel::All, 0);
1185        assert_eq!(r.ring, NotifyLevel::Nothing);
1186    }
1187
1188    #[test]
1189    fn a_lapsed_timer_stops_muting_without_anything_being_written() {
1190        let prefs = at(None, 5_000);
1191        assert!(resolve_from(prefs, ScopePrefs::default(), NotifyLevel::All, 4_999).muted);
1192        assert!(!resolve_from(prefs, ScopePrefs::default(), NotifyLevel::All, 5_000).muted);
1193    }
1194
1195    #[test]
1196    fn the_legacy_list_names_a_channel_its_community_muted() {
1197        // Chain-resolved, so a client that predates levels goes quiet in the same rooms.
1198        let channel = in_legacy_mute_list(ScopePrefs::default(), at(None, MUTE_FOREVER), 0);
1199        assert!(channel);
1200    }
1201
1202    #[test]
1203    fn publishing_and_applying_the_legacy_list_agree() {
1204        // The bug this guards: publish with one predicate and apply with another, and
1205        // an inherited mute round-trips into a permanent per-channel one.
1206        let community = at(None, MUTE_FOREVER);
1207        let channel = ScopePrefs::default();
1208        let published = in_legacy_mute_list(channel, community, 0);
1209        let on_apply = in_legacy_mute_list(channel, community, 0);
1210        assert_eq!(published, on_apply, "the applier must read what the publisher wrote");
1211        assert!(published);
1212    }
1213
1214    #[test]
1215    fn a_timed_mute_never_enters_the_legacy_list() {
1216        // It carries no deadline, so anything in it comes back indefinite, and the
1217        // expiry that should correct that happens at boot where publishing is barred.
1218        assert!(!in_legacy_mute_list(at(None, 9_000), ScopePrefs::default(), 0));
1219        assert!(!in_legacy_mute_list(ScopePrefs::default(), at(None, 9_000), 0));
1220        assert!(in_legacy_mute_list(at(None, MUTE_FOREVER), ScopePrefs::default(), 0));
1221    }
1222
1223    #[test]
1224    fn a_lapsed_indefinite_free_scope_leaves_the_legacy_list() {
1225        let expired = at(None, 5_000);
1226        assert!(!in_legacy_mute_list(expired, ScopePrefs::default(), 6_000));
1227    }
1228
1229    #[test]
1230    fn sweep_picks_exactly_the_timers_that_have_arrived() {
1231        // Mirrors `db::notify::clear_expired_mutes`'s `mute_until > 0 AND <= ?1`.
1232        let lapsed = |until: i64, now: i64| until > MUTE_OFF && until <= now;
1233        assert!(!lapsed(MUTE_FOREVER, 10_000), "indefinite never lapses");
1234        assert!(!lapsed(MUTE_OFF, 10_000), "unmuted has no timer");
1235        assert!(lapsed(10_000, 10_000), "an expiry that has arrived is over");
1236        assert!(!lapsed(10_001, 10_000));
1237    }
1238
1239    #[test]
1240    fn scope_prefs_round_trip_through_the_wire_shape() {
1241        let prefs = ScopePrefs {
1242            level: Some(NotifyLevel::Mentions),
1243            mute_until: 1_700_000_000_000,
1244            suppress_everyone: Some(true),
1245        };
1246        assert_eq!(ScopePrefs::from_wire(&prefs.to_wire()), prefs);
1247        // An entry that says nothing must come back as the default, or a sync
1248        // would keep resurrecting rows the writer meant to drop.
1249        assert!(ScopePrefs::from_wire(&crate::synced_prefs::NotifyEntry::default()).is_default());
1250    }
1251
1252    #[test]
1253    fn level_round_trips_through_both_wire_forms() {
1254        for level in [NotifyLevel::All, NotifyLevel::Mentions, NotifyLevel::Nothing] {
1255            assert_eq!(NotifyLevel::from_u8(level.as_u8()), Some(level));
1256            assert_eq!(NotifyLevel::from_label(level.as_str()), Some(level));
1257        }
1258        // The sync payload predates the rename, so both spellings must read.
1259        assert_eq!(NotifyLevel::from_label("none"), Some(NotifyLevel::Nothing));
1260        assert_eq!(NotifyLevel::from_label("whatever"), None);
1261        assert_eq!(NotifyLevel::from_u8(9), None);
1262    }
1263}