1use std::collections::HashMap;
14use std::sync::{Arc, RwLock};
15
16#[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 pub fn quieter_of(self, other: Self) -> Self {
58 if self >= other { self } else { other }
59 }
60}
61
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum MessageClass {
67 Everyone,
68 Mention,
69 Normal,
70}
71
72pub 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
81pub const MUTE_FOREVER: i64 = -1;
83pub 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#[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
114pub struct Resolved {
115 pub level: NotifyLevel,
117 pub muted: bool,
118 pub ring: NotifyLevel,
120}
121
122#[derive(Default)]
127struct Store {
128 loaded: bool,
129 scopes: HashMap<String, ScopePrefs>,
130 live_channels: Option<std::collections::HashSet<[u8; 32]>>,
134 communities: Option<std::collections::HashSet<[u8; 32]>>,
137}
138
139fn 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
150pub 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
171pub fn is_loaded() -> bool {
176 store().read().map(|g| g.loaded).unwrap_or(false)
177}
178
179pub 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
189pub fn invalidate_communities() {
193 if let Ok(mut g) = store().write() {
194 g.live_channels = None;
195 g.communities = None;
196 }
197}
198
199pub 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 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
221pub fn default_level(group_id: Option<&str>) -> NotifyLevel {
224 if group_id.is_some_and(is_community) { NotifyLevel::Mentions } else { NotifyLevel::All }
225}
226
227pub 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 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
260pub 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 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
294pub 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
315pub 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
327pub 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
336fn community_of(chat: &crate::chat::Chat) -> Option<&str> {
338 chat.metadata.community_id()
339}
340
341pub 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
354pub 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
364pub 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
370pub 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
383pub 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 || (chat.muted && !own.muted_at(now_ms()) && !parent.muted_at(now_ms()))
393}
394
395pub 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
407pub 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
423pub 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
462impl 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
484pub 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
493pub fn apply_wire(map: &crate::synced_prefs::NotifyMap) -> Result<Vec<String>, String> {
496 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
528pub enum ContentPrivacy {
529 Full,
531 HideContent,
533 HideSender,
535 HideAll,
537}
538
539impl ContentPrivacy {
540 pub fn load() -> Self {
543 Self::effective(Self::load_base(), &crate::synced_prefs::load_settings().streamer)
544 }
545
546 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 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 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 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
603pub const STREAM_MASK: &str = "•••••";
605
606#[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 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 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#[derive(Debug, Clone, PartialEq, Eq)]
645pub struct Sender {
646 pub name: String,
647 pub avatar: Option<String>,
648}
649
650pub 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
666pub 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
680pub 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 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
716pub 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
729pub 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
783fn 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#[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 pub group: Option<String>,
805 pub group_avatar: Option<String>,
806}
807
808impl Preview {
809 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 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 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 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 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 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 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 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 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}