use std::collections::HashMap;
use std::sync::{Arc, RwLock};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[repr(u8)]
pub enum NotifyLevel {
All = 0,
Mentions = 1,
Nothing = 2,
}
impl NotifyLevel {
pub fn as_u8(self) -> u8 {
self as u8
}
pub fn from_u8(v: u8) -> Option<Self> {
match v {
0 => Some(Self::All),
1 => Some(Self::Mentions),
2 => Some(Self::Nothing),
_ => None,
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::All => "all",
Self::Mentions => "mentions",
Self::Nothing => "nothing",
}
}
pub fn from_label(s: &str) -> Option<Self> {
match s {
"all" => Some(Self::All),
"mentions" => Some(Self::Mentions),
"nothing" | "none" => Some(Self::Nothing),
_ => None,
}
}
pub fn quieter_of(self, other: Self) -> Self {
if self >= other { self } else { other }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessageClass {
Everyone,
Mention,
Normal,
}
pub fn passes(level: NotifyLevel, class: MessageClass) -> bool {
match level {
NotifyLevel::All => true,
NotifyLevel::Mentions => !matches!(class, MessageClass::Normal),
NotifyLevel::Nothing => false,
}
}
pub const MUTE_FOREVER: i64 = -1;
pub const MUTE_OFF: i64 = 0;
pub fn is_muted_at(mute_until: i64, now_ms: i64) -> bool {
mute_until == MUTE_FOREVER || mute_until > now_ms
}
pub fn now_ms() -> i64 {
crate::clock::now_ms() as i64
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ScopePrefs {
pub level: Option<NotifyLevel>,
pub mute_until: i64,
pub suppress_everyone: Option<bool>,
}
impl ScopePrefs {
pub fn is_default(&self) -> bool {
self.level.is_none() && self.mute_until == MUTE_OFF && self.suppress_everyone.is_none()
}
pub fn muted_at(&self, now_ms: i64) -> bool {
is_muted_at(self.mute_until, now_ms)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Resolved {
pub level: NotifyLevel,
pub muted: bool,
pub ring: NotifyLevel,
}
#[derive(Default)]
struct Store {
loaded: bool,
scopes: HashMap<String, ScopePrefs>,
live_channels: Option<std::collections::HashSet<[u8; 32]>>,
communities: Option<std::collections::HashSet<[u8; 32]>>,
}
fn holds(set: &std::collections::HashSet<[u8; 32]>, id: &str) -> bool {
crate::community::id32_from_hex(id).is_some_and(|b| set.contains(&b))
}
struct NotifyStore;
fn store() -> Arc<RwLock<Store>> {
crate::db::current_session().scoped::<NotifyStore, _>()
}
pub fn warm() {
let cell = store();
if cell.read().map(|g| g.loaded).unwrap_or(false) {
return;
}
let rows = match crate::db::notify::load_all() {
Ok(rows) => rows,
Err(_) => return,
};
if let Ok(mut g) = cell.write() {
g.scopes = rows;
g.loaded = true;
};
}
pub fn is_loaded() -> bool {
store().read().map(|g| g.loaded).unwrap_or(false)
}
pub fn invalidate() {
if let Ok(mut g) = store().write() {
g.loaded = false;
g.scopes.clear();
g.live_channels = None;
g.communities = None;
}
}
pub fn invalidate_communities() {
if let Ok(mut g) = store().write() {
g.live_channels = None;
g.communities = None;
}
}
pub fn is_community(community_id: &str) -> bool {
let cell = store();
if let Ok(g) = cell.read() {
if let Some(set) = g.communities.as_ref() {
return holds(set, community_id);
}
}
let ids = match crate::db::community::community_ids_beyond_group_chat() {
Ok(ids) => ids,
Err(_) => return false,
};
let found = holds(&ids, community_id);
if let Ok(mut g) = cell.write() {
g.communities = Some(ids);
}
found
}
pub fn default_level(group_id: Option<&str>) -> NotifyLevel {
if group_id.is_some_and(is_community) { NotifyLevel::Mentions } else { NotifyLevel::All }
}
pub fn channel_is_listed(channel_id: &str) -> bool {
let cell = store();
if let Ok(g) = cell.read() {
if let Some(set) = g.live_channels.as_ref() {
return holds(set, channel_id);
}
}
let ids: std::collections::HashSet<[u8; 32]> = match crate::db::notify::live_channel_ids() {
Ok(ids) => ids.iter().filter_map(|id| crate::community::id32_from_hex(id)).collect(),
Err(_) => return true,
};
let listed = holds(&ids, channel_id);
if let Ok(mut g) = cell.write() {
g.live_channels = Some(ids);
}
listed
}
pub fn prefs(scope_id: &str) -> ScopePrefs {
store()
.read()
.ok()
.and_then(|g| g.scopes.get(scope_id).copied())
.unwrap_or_default()
}
pub fn all_prefs() -> HashMap<String, ScopePrefs> {
store().read().map(|g| g.scopes.clone()).unwrap_or_default()
}
pub fn set_prefs(scope_id: &str, next: ScopePrefs) -> Result<(), String> {
warm();
crate::db::notify::save(scope_id, &next)?;
if let Ok(mut g) = store().write() {
if next.is_default() {
g.scopes.remove(scope_id);
} else {
g.scopes.insert(scope_id.to_string(), next);
}
}
crate::push::controls_changed();
Ok(())
}
pub fn set_level(scope_id: &str, level: Option<NotifyLevel>) -> Result<(), String> {
let mut next = prefs(scope_id);
next.level = level;
set_prefs(scope_id, next)
}
pub fn set_mute(scope_id: &str, mute_until: i64) -> Result<(), String> {
let mut next = prefs(scope_id);
next.mute_until = mute_until;
set_prefs(scope_id, next)
}
pub fn set_suppress_everyone(scope_id: &str, suppress: Option<bool>) -> Result<(), String> {
let mut next = prefs(scope_id);
next.suppress_everyone = suppress;
set_prefs(scope_id, next)
}
pub fn everyone_allowed(community_id: Option<&str>) -> bool {
let globally_muted = crate::db::settings::get_sql_setting("notif_mute_everyone".to_string())
.ok()
.flatten()
.is_some_and(|v| v == "true");
if globally_muted {
return false;
}
!community_id.is_some_and(|cid| prefs(cid).suppress_everyone.unwrap_or(false))
}
pub fn resolve(scope_id: &str, community_id: Option<&str>, now_ms: i64) -> Resolved {
let own = prefs(scope_id);
let parent = community_id
.filter(|cid| *cid != scope_id)
.map(prefs)
.unwrap_or_default();
let fallback = default_level(Some(community_id.unwrap_or(scope_id)));
resolve_from(own, parent, fallback, now_ms)
}
pub fn resolve_from(own: ScopePrefs, parent: ScopePrefs, fallback: NotifyLevel, now_ms: i64) -> Resolved {
let level = own.level.or(parent.level).unwrap_or(fallback);
let muted = own.muted_at(now_ms) || parent.muted_at(now_ms);
let ring = level.quieter_of(if muted { NotifyLevel::Mentions } else { NotifyLevel::All });
Resolved { level, muted, ring }
}
fn community_of(chat: &crate::chat::Chat) -> Option<&str> {
chat.metadata.community_id()
}
pub fn resolve_chat(chat: &crate::chat::Chat) -> Resolved {
let mut resolved = resolve(&chat.id, community_of(chat), now_ms());
if chat.muted && !resolved.muted {
resolved.muted = true;
resolved.ring = resolved.level.quieter_of(NotifyLevel::Mentions);
}
resolved
}
pub fn ring_for_chat(chat: &crate::chat::Chat) -> NotifyLevel {
resolve_chat(chat).ring
}
pub fn muted_for_chat(chat: &crate::chat::Chat) -> bool {
resolve_chat(chat).muted
}
pub fn community_muted_for_chat(chat: &crate::chat::Chat) -> bool {
community_of(chat).is_some_and(|id| prefs(id).muted_at(now_ms()))
}
pub fn in_legacy_mute_list(own: ScopePrefs, parent: ScopePrefs, now_ms: i64) -> bool {
(own.muted_at(now_ms) || parent.muted_at(now_ms))
&& (own.mute_until == MUTE_FOREVER || parent.mute_until == MUTE_FOREVER)
}
pub fn legacy_muted_for_chat(chat: &crate::chat::Chat) -> bool {
let own = prefs(&chat.id);
let parent = community_of(chat)
.filter(|cid| *cid != chat.id)
.map(prefs)
.unwrap_or_default();
in_legacy_mute_list(own, parent, now_ms())
|| (chat.muted && !own.muted_at(now_ms()) && !parent.muted_at(now_ms()))
}
pub fn everyone_pings_for_chat(chat: &crate::chat::Chat) -> bool {
!community_of(chat)
.map(prefs)
.and_then(|p| p.suppress_everyone)
.unwrap_or(false)
}
pub fn next_expiry(now_ms: i64) -> Option<i64> {
store().read().ok().and_then(|g| {
g.scopes
.values()
.map(|p| p.mute_until)
.filter(|&u| u > now_ms)
.min()
})
}
pub fn sweep_expired(now_ms: i64) -> Vec<String> {
warm();
let cell = store();
let lapsed: Vec<String> = match cell.read() {
Ok(g) => g
.scopes
.iter()
.filter(|(_, p)| p.mute_until > MUTE_OFF && p.mute_until <= now_ms)
.map(|(id, _)| id.clone())
.collect(),
Err(_) => return Vec::new(),
};
if lapsed.is_empty() {
return lapsed;
}
if crate::db::notify::clear_expired_mutes(now_ms).is_err() {
return Vec::new();
}
if let Ok(mut g) = cell.write() {
for id in &lapsed {
let drop_row = match g.scopes.get_mut(id) {
Some(p) => {
p.mute_until = MUTE_OFF;
p.is_default()
}
None => false,
};
if drop_row {
g.scopes.remove(id);
}
}
}
lapsed
}
impl ScopePrefs {
pub fn to_wire(self) -> crate::synced_prefs::NotifyEntry {
crate::synced_prefs::NotifyEntry {
level: self.level.map(|l| l.as_str().to_string()),
mute_until: self.mute_until,
suppress_everyone: self.suppress_everyone,
}
}
pub fn from_wire(entry: &crate::synced_prefs::NotifyEntry) -> Self {
Self {
level: entry.level.as_deref().and_then(NotifyLevel::from_label),
mute_until: entry.mute_until,
suppress_everyone: entry.suppress_everyone,
}
}
}
pub fn to_wire() -> crate::synced_prefs::NotifyMap {
let mut map = crate::synced_prefs::NotifyMap::default();
for (scope_id, prefs) in all_prefs() {
let _ = map.set(&scope_id, prefs.to_wire());
}
map
}
pub fn apply_wire(map: &crate::synced_prefs::NotifyMap) -> Result<Vec<String>, String> {
warm();
if !is_loaded() {
return Err("notification preferences not read yet".to_string());
}
let next: HashMap<String, ScopePrefs> = map
.scopes
.iter()
.map(|(id, entry)| (id.clone(), ScopePrefs::from_wire(entry)))
.filter(|(_, p)| !p.is_default())
.collect();
let before = all_prefs();
crate::db::notify::replace_all(&next)?;
if let Ok(mut g) = store().write() {
g.scopes = next.clone();
g.loaded = true;
}
let mut moved: Vec<String> = next
.iter()
.filter(|(id, p)| before.get(*id) != Some(p))
.map(|(id, _)| id.clone())
.collect();
crate::push::controls_changed();
moved.extend(before.keys().filter(|id| !next.contains_key(*id)).cloned());
Ok(moved)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContentPrivacy {
Full,
HideContent,
HideSender,
HideAll,
}
impl ContentPrivacy {
pub fn load() -> Self {
Self::effective(Self::load_base(), &crate::synced_prefs::load_settings().streamer)
}
pub fn load_base() -> Self {
Self::parse(crate::db::get_sql_setting("notif_content_privacy".to_string()).ok().flatten().as_deref())
}
pub fn effective(base: Self, streamer: &crate::synced_prefs::StreamerSettings) -> Self {
if streamer.on {
base.join(Self::parse(Some(&streamer.notif)))
} else {
base
}
}
pub fn join(self, other: Self) -> Self {
Self::from_bits(self.bits() | other.bits())
}
fn bits(self) -> u8 {
match self {
Self::Full => 0b00,
Self::HideContent => 0b01,
Self::HideSender => 0b10,
Self::HideAll => 0b11,
}
}
fn from_bits(bits: u8) -> Self {
match bits & 0b11 {
0b00 => Self::Full,
0b01 => Self::HideContent,
0b10 => Self::HideSender,
_ => Self::HideAll,
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Full => "full",
Self::HideContent => "hide_content",
Self::HideSender => "hide_sender",
Self::HideAll => "hide_all",
}
}
fn parse(value: Option<&str>) -> Self {
match value {
Some("hide_content") => Self::HideContent,
Some("hide_sender") => Self::HideSender,
Some("hide_all") => Self::HideAll,
_ => Self::Full,
}
}
}
pub const STREAM_MASK: &str = "•••••";
#[derive(Debug, Clone, Default)]
pub struct StreamGate {
on: bool,
me: Option<String>,
}
impl StreamGate {
pub fn load() -> Self {
if !crate::synced_prefs::load_settings().streamer.on {
return Self::default();
}
let me = crate::state::my_public_key()
.and_then(|pk| nostr_sdk::prelude::ToBech32::to_bech32(&pk).ok())
.or_else(|| crate::db::get_current_account().ok());
Self { on: true, me }
}
pub fn new(on: bool, me: Option<String>) -> Self {
Self { on, me }
}
pub fn is_on(&self) -> bool {
self.on
}
pub fn hides(&self, npub: &str, profile: Option<&crate::profile::Profile>) -> bool {
if !self.on || self.me.as_deref() == Some(npub) {
return false;
}
!profile.is_some_and(|p| p.flags.is_mine() || p.flags.is_stream_consent())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sender {
pub name: String,
pub avatar: Option<String>,
}
pub fn sender(state: &crate::state::ChatState, gate: &StreamGate, npub: &str, fallback: &str) -> Sender {
let profile = state.get_profile(npub);
if gate.hides(npub, profile) {
return Sender { name: STREAM_MASK.to_string(), avatar: None };
}
let Some(p) = profile else {
return Sender { name: fallback.to_string(), avatar: None };
};
Sender {
name: display_name(p).unwrap_or(fallback).to_string(),
avatar: p.has_avatar_cached().then(|| p.avatar_cached().into_owned()),
}
}
pub fn sender_in(state: &crate::state::ChatState, gate: &StreamGate, npub: &str, fallback: &str, nickname: Option<String>) -> Sender {
let shown = sender(state, gate, npub, fallback);
let profile = state.get_profile(npub);
match nickname {
Some(name) if !gate.hides(npub, profile) && profile.is_none_or(|p| p.nickname().is_empty()) => Sender { name, ..shown },
_ => shown,
}
}
fn display_name(p: &crate::profile::Profile) -> Option<&str> {
[p.nickname(), p.name(), p.display_name()].into_iter().find(|n| !n.is_empty())
}
pub fn strip_ansi(content: &str) -> std::borrow::Cow<'_, str> {
if !content.contains('\x1b') {
return std::borrow::Cow::Borrowed(content);
}
let mut out = String::with_capacity(content.len());
let mut chars = content.chars().peekable();
while let Some(c) = chars.next() {
if c != '\x1b' {
out.push(c);
continue;
}
match chars.peek() {
Some('[') => {
chars.next();
while let Some(&n) = chars.peek() {
if !('\x20'..='\x3f').contains(&n) {
if ('\x40'..='\x7e').contains(&n) {
chars.next();
}
break;
}
chars.next();
}
}
Some(n) if ('\x40'..='\x5f').contains(n) => {
chars.next();
}
_ => {}
}
}
std::borrow::Cow::Owned(out)
}
pub fn resolve_mentions(content: &str, state: &crate::state::ChatState, gate: &StreamGate) -> String {
scan_mentions(content, |npub| {
let profile = state.get_profile(npub);
if gate.hides(npub, profile) {
return Some(STREAM_MASK.to_string());
}
profile.and_then(display_name).map(str::to_string)
})
}
pub fn scan_mentions<F: Fn(&str) -> Option<String>>(content: &str, lookup: F) -> String {
const NPUB_LEN: usize = 63;
const BECH32: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
let bytes = content.as_bytes();
let len = bytes.len();
let mut result = String::with_capacity(len);
let mut cursor = 0;
let mut i = 0;
while i + NPUB_LEN <= len {
if bytes[i..].starts_with(b"nprofile1") {
let end = i + 9 + bytes[i + 9..].iter().take_while(|b| BECH32.contains(&b.to_ascii_lowercase())).count();
let npub = <nostr_sdk::prelude::Nip19Profile as nostr_sdk::prelude::FromBech32>::from_bech32(&content[i..end])
.ok()
.and_then(|p| nostr_sdk::prelude::ToBech32::to_bech32(&p.public_key).ok());
if let Some(name) = npub.as_deref().and_then(&lookup) {
let mstart = mention_start(bytes, i);
result.push_str(&content[cursor..mstart]);
result.push('@');
result.push_str(&name);
cursor = end;
}
i = end;
continue;
}
let is_npub = &bytes[i..i + 5] == b"npub1"
&& bytes[i + 5..i + NPUB_LEN]
.iter()
.all(|b| BECH32.contains(&b.to_ascii_lowercase()));
if is_npub {
let npub_end = i + NPUB_LEN;
if let Some(name) = lookup(&content[i..npub_end]) {
let mstart = mention_start(bytes, i);
result.push_str(&content[cursor..mstart]);
result.push('@');
result.push_str(&name);
cursor = npub_end;
}
i = npub_end;
continue;
}
i += 1;
}
result.push_str(&content[cursor..]);
result
}
fn mention_start(bytes: &[u8], i: usize) -> usize {
if i >= 1 && bytes[i - 1] == b'@' {
i - 1
} else if i >= 6 && &bytes[i - 6..i] == b"nostr:" {
i - 6
} else {
i
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Preview {
pub title: String,
pub body: String,
pub sender: Option<String>,
pub avatar: Option<String>,
pub group: Option<String>,
pub group_avatar: Option<String>,
}
impl Preview {
pub fn apply(&mut self, privacy: ContentPrivacy) {
match privacy {
ContentPrivacy::Full => {}
ContentPrivacy::HideContent => {
self.body = if self.group.is_some() { "Sent a message" } else { "Sent you a message" }.to_string();
}
ContentPrivacy::HideSender => {
self.title = self.group.clone().unwrap_or_else(|| "New message".to_string());
self.sender = None;
self.avatar = None;
}
ContentPrivacy::HideAll => {
*self = Preview {
title: "Vector".to_string(),
body: "You received a message".to_string(),
..Default::default()
};
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn strip_ansi_drops_escape_sequences() {
assert_eq!(strip_ansi("plain"), "plain");
assert_eq!(strip_ansi("\x1b[2;31mred\x1b[0m and \x1b[38;2;88;101;242mblurple\x1b[0m"), "red and blurple");
assert_eq!(strip_ansi("a\x1b[1;4mb\x1b[mc"), "abc");
assert_eq!(strip_ansi("lone \x1b and \x1bM up, cut \x1b[31"), "lone and up, cut ");
assert_eq!(strip_ansi("\x1b[31m\u{1F600}\x1b[\u{e9}"), "\u{1F600}\u{e9}");
}
fn dm() -> Preview {
Preview {
title: "Alice".into(),
body: "see you at 8".into(),
sender: Some("Alice".into()),
avatar: Some("/a.png".into()),
..Default::default()
}
}
fn channel() -> Preview {
Preview {
title: "Alice - Rust Club".into(),
body: "see you at 8".into(),
sender: Some("Alice".into()),
avatar: Some("/a.png".into()),
group: Some("Rust Club".into()),
group_avatar: Some("/club.png".into()),
}
}
#[test]
fn content_privacy_reads_every_stored_value() {
assert_eq!(ContentPrivacy::parse(None), ContentPrivacy::Full);
assert_eq!(ContentPrivacy::parse(Some("full")), ContentPrivacy::Full);
assert_eq!(ContentPrivacy::parse(Some("hide_content")), ContentPrivacy::HideContent);
assert_eq!(ContentPrivacy::parse(Some("hide_sender")), ContentPrivacy::HideSender);
assert_eq!(ContentPrivacy::parse(Some("hide_all")), ContentPrivacy::HideAll);
assert_eq!(ContentPrivacy::parse(Some("true")), ContentPrivacy::Full);
}
#[test]
fn hiding_the_sender_keeps_the_message_and_the_community() {
let mut p = dm();
p.apply(ContentPrivacy::HideSender);
assert_eq!((p.title.as_str(), p.body.as_str()), ("New message", "see you at 8"));
assert_eq!((p.sender, p.avatar), (None, None));
let mut p = channel();
p.apply(ContentPrivacy::HideSender);
assert_eq!((p.title.as_str(), p.body.as_str()), ("Rust Club", "see you at 8"));
assert_eq!((p.sender, p.avatar), (None, None));
assert_eq!(p.group_avatar.as_deref(), Some("/club.png"));
}
#[test]
fn hiding_the_message_keeps_the_sender() {
let mut p = dm();
p.apply(ContentPrivacy::HideContent);
assert_eq!((p.title.as_str(), p.body.as_str()), ("Alice", "Sent you a message"));
assert_eq!(p.avatar.as_deref(), Some("/a.png"));
let mut p = channel();
p.apply(ContentPrivacy::HideContent);
assert_eq!(p.body, "Sent a message");
assert_eq!(p.sender.as_deref(), Some("Alice"));
}
#[test]
fn hiding_everything_leaves_nothing_identifying() {
for mut p in [dm(), channel()] {
p.apply(ContentPrivacy::HideAll);
assert_eq!(p, Preview { title: "Vector".into(), body: "You received a message".into(), ..Default::default() });
}
}
#[test]
fn content_privacy_is_idempotent() {
for privacy in [ContentPrivacy::Full, ContentPrivacy::HideContent, ContentPrivacy::HideSender, ContentPrivacy::HideAll] {
for base in [dm(), channel()] {
let mut once = base.clone();
once.apply(privacy);
let mut twice = once.clone();
twice.apply(privacy);
assert_eq!(once, twice, "{privacy:?}");
}
}
}
const ALL_PRIVACY: [ContentPrivacy; 4] =
[ContentPrivacy::Full, ContentPrivacy::HideContent, ContentPrivacy::HideSender, ContentPrivacy::HideAll];
#[test]
fn privacy_joins_as_a_two_bit_union() {
for x in ALL_PRIVACY {
assert_eq!(ContentPrivacy::Full.join(x), x, "Full adds nothing to {x:?}");
assert_eq!(x.join(ContentPrivacy::Full), x);
assert_eq!(x.join(x), x, "joining {x:?} with itself is idempotent");
assert_eq!(x.join(ContentPrivacy::HideAll), ContentPrivacy::HideAll);
for y in ALL_PRIVACY {
assert_eq!(x.join(y), y.join(x), "{x:?} with {y:?} commutes");
}
}
assert_eq!(ContentPrivacy::HideContent.join(ContentPrivacy::HideSender), ContentPrivacy::HideAll);
}
#[test]
fn joining_first_hides_more_than_applying_twice() {
let mut twice = channel();
twice.apply(ContentPrivacy::HideSender);
twice.apply(ContentPrivacy::HideContent);
let mut joined = channel();
joined.apply(ContentPrivacy::HideSender.join(ContentPrivacy::HideContent));
assert_ne!(twice, joined, "applying in turn leaves the community showing");
assert_eq!(joined.group, None);
}
#[test]
fn privacy_spelling_round_trips() {
for x in ALL_PRIVACY {
assert_eq!(ContentPrivacy::parse(Some(x.as_str())), x);
}
assert_eq!(ContentPrivacy::parse(Some("none")), ContentPrivacy::Full, "the overlay's off spelling");
}
fn streaming(on: bool, notif: &str) -> crate::synced_prefs::StreamerSettings {
crate::synced_prefs::StreamerSettings { on, notif: notif.into(), ..Default::default() }
}
#[test]
fn the_overlay_counts_only_while_live() {
let base = ContentPrivacy::HideContent;
assert_eq!(ContentPrivacy::effective(base, &streaming(false, "hide_sender")), base);
assert_eq!(ContentPrivacy::effective(base, &streaming(true, "hide_sender")), ContentPrivacy::HideAll);
assert_eq!(ContentPrivacy::effective(base, &streaming(true, "none")), base);
assert_eq!(
ContentPrivacy::effective(ContentPrivacy::Full, &streaming(true, "hide_content")),
ContentPrivacy::HideContent
);
}
fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
crate::db::close_database();
crate::db::clear_id_caches();
use nostr_sdk::prelude::ToBech32;
let tmp = tempfile::tempdir().unwrap();
let account = nostr_sdk::prelude::Keys::generate().public_key().to_bech32().unwrap();
std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
crate::db::set_current_account(account.clone()).unwrap();
crate::db::init_database(&account).unwrap();
(tmp, guard)
}
#[test]
fn load_reads_the_setting_and_the_overlay() {
let (_tmp, _guard) = init_test_db();
use crate::synced_prefs::{save_local_raw, Pref, SyncedSettings};
crate::db::set_sql_setting("notif_content_privacy".into(), "hide_content".into()).unwrap();
let mut settings = SyncedSettings::default();
settings.streamer = streaming(true, "hide_sender");
save_local_raw(Pref::Settings, &settings.to_json()).unwrap();
assert_eq!(ContentPrivacy::load_base(), ContentPrivacy::HideContent);
assert_eq!(ContentPrivacy::load(), ContentPrivacy::HideAll);
settings.streamer.on = false;
save_local_raw(Pref::Settings, &settings.to_json()).unwrap();
assert_eq!(ContentPrivacy::load(), ContentPrivacy::HideContent, "off, the overlay is ignored");
}
const ME: &str = "npub1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq";
const FAN: &str = "npub1pppppppppppppppppppppppppppppppppppppppppppppppppppppppppp";
const SHY: &str = "npub1zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
const STRANGER: &str = "npub1rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr";
fn people() -> crate::state::ChatState {
let mut state = crate::state::ChatState::new();
let person = |name: &str, consent: bool| {
let mut p = crate::profile::Profile::new();
p.set_name(name);
p.set_avatar_cached(&format!("/{name}.png"));
p.flags.set_stream_consent(consent);
p
};
state.insert_or_replace_profile(ME, person("Me", false));
let mut fan = person("Fan", true);
fan.set_nickname("Bestie");
state.insert_or_replace_profile(FAN, fan);
state.insert_or_replace_profile(SHY, person("Shy", false));
state
}
#[test]
fn streaming_masks_everyone_but_me_and_those_who_opted_in() {
let state = people();
let live = StreamGate::new(true, Some(ME.into()));
let shown = |npub| sender(&state, &live, npub, "New Message");
assert_eq!(shown(ME), Sender { name: "Me".into(), avatar: Some("/Me.png".into()) });
assert_eq!(shown(FAN), Sender { name: "Bestie".into(), avatar: Some("/Fan.png".into()) }, "opted in reads as normal, nickname too");
for hidden in [SHY, STRANGER] {
assert_eq!(shown(hidden), Sender { name: STREAM_MASK.into(), avatar: None }, "{hidden}");
}
assert_eq!(STREAM_MASK.chars().count(), 5);
let off = StreamGate::default();
assert_eq!(sender(&state, &off, SHY, "New Message").name, "Shy");
assert_eq!(sender(&state, &off, STRANGER, "New Message"), Sender { name: "New Message".into(), avatar: None });
}
#[test]
fn my_own_profile_shows_even_without_an_identity() {
let mut state = people();
state.get_profile_mut(SHY).unwrap().flags.set_mine(true);
let live = StreamGate::new(true, None);
assert_eq!(sender(&state, &live, SHY, "x").name, "Shy");
assert_eq!(sender(&state, &live, ME, "x").name, STREAM_MASK, "another local account is hidden");
}
#[test]
fn mentions_are_masked_while_live_and_named_otherwise() {
let state = people();
let text = format!("@{SHY} meet nostr:{FAN} and {STRANGER}, from @{ME}");
let live = StreamGate::new(true, Some(ME.into()));
assert_eq!(resolve_mentions(&text, &state, &live), "@••••• meet @Bestie and @•••••, from @Me");
let off = StreamGate::default();
assert_eq!(
resolve_mentions(&text, &state, &off),
format!("@Shy meet @Bestie and {STRANGER}, from @Me"),
"an unknown npub stays as written when not live"
);
}
#[test]
fn an_nprofile_mention_reads_as_the_npub_it_encodes() {
use nostr_sdk::prelude::{Keys, Nip19Profile, RelayUrl, ToBech32};
let mut state = people();
let pk = Keys::generate().public_key();
let npub = pk.to_bech32().unwrap();
let mut p = crate::profile::Profile::new();
p.set_name("Hidden");
state.insert_or_replace_profile(&npub, p);
let relay = RelayUrl::parse("wss://relay.example.com").unwrap();
let nprofile = Nip19Profile::new(pk, [relay]).to_bech32().unwrap();
let live = StreamGate::new(true, Some(ME.into()));
assert_eq!(resolve_mentions(&format!("ask nostr:{nprofile} now"), &state, &live), "ask @••••• now");
assert_eq!(resolve_mentions(&format!("ask @{nprofile}"), &state, &StreamGate::default()), "ask @Hidden");
let stranger = Nip19Profile::new(Keys::generate().public_key(), []).to_bech32().unwrap();
assert_eq!(resolve_mentions(&format!("hi {stranger}"), &state, &live), "hi @•••••", "unknown is hidden too");
assert_eq!(scan_mentions("nprofile1qqqq broken", |_| Some("x".into())), "nprofile1qqqq broken");
}
#[test]
fn mention_scanner_reads_every_form() {
let npub = format!("npub1{}", "q".repeat(58));
let unknown = format!("npub1{}", "p".repeat(58));
let known: &str = &npub;
let lookup = |n: &str| (n == known).then(|| "Alice".to_string());
assert_eq!(scan_mentions(&format!("hey @{npub}!"), lookup), "hey @Alice!");
assert_eq!(scan_mentions(&format!("hey nostr:{npub}!"), lookup), "hey @Alice!");
assert_eq!(scan_mentions(&format!("hey {npub}!"), lookup), "hey @Alice!");
assert_eq!(scan_mentions(&format!("hi nostr:{unknown}"), lookup), format!("hi nostr:{unknown}"));
assert_eq!(scan_mentions(&format!("{npub} and nostr:{npub} done"), lookup), "@Alice and @Alice done");
assert_eq!(scan_mentions("just a normal line 🎉", lookup), "just a normal line 🎉");
}
#[test]
fn mute_clamps_the_level_to_mentions() {
assert_eq!(NotifyLevel::All.quieter_of(NotifyLevel::Mentions), NotifyLevel::Mentions);
assert_eq!(NotifyLevel::Nothing.quieter_of(NotifyLevel::Mentions), NotifyLevel::Nothing);
assert_eq!(NotifyLevel::Mentions.quieter_of(NotifyLevel::All), NotifyLevel::Mentions);
}
#[test]
fn level_decides_which_classes_ring() {
for class in [MessageClass::Everyone, MessageClass::Mention, MessageClass::Normal] {
assert!(passes(NotifyLevel::All, class));
assert!(!passes(NotifyLevel::Nothing, class));
}
assert!(passes(NotifyLevel::Mentions, MessageClass::Mention));
assert!(passes(NotifyLevel::Mentions, MessageClass::Everyone));
assert!(!passes(NotifyLevel::Mentions, MessageClass::Normal));
}
#[test]
fn mute_sentinels() {
assert!(is_muted_at(MUTE_FOREVER, 10_000));
assert!(!is_muted_at(MUTE_OFF, 10_000));
assert!(is_muted_at(10_001, 10_000));
assert!(!is_muted_at(10_000, 10_000), "an expiry that has arrived is over");
}
#[test]
fn a_scope_at_every_default_stores_nothing() {
assert!(ScopePrefs::default().is_default());
assert!(!ScopePrefs { mute_until: MUTE_FOREVER, ..Default::default() }.is_default());
assert!(!ScopePrefs { level: Some(NotifyLevel::Nothing), ..Default::default() }.is_default());
}
fn at(level: Option<NotifyLevel>, mute_until: i64) -> ScopePrefs {
ScopePrefs { level, mute_until, suppress_everyone: None }
}
#[test]
fn a_channel_opinion_beats_its_community() {
let r = resolve_from(at(Some(NotifyLevel::All), 0), at(Some(NotifyLevel::Nothing), 0), NotifyLevel::All, 0);
assert_eq!(r.level, NotifyLevel::All);
assert_eq!(r.ring, NotifyLevel::All);
}
#[test]
fn a_channel_with_no_opinion_takes_its_community() {
let r = resolve_from(at(None, 0), at(Some(NotifyLevel::Mentions), 0), NotifyLevel::All, 0);
assert_eq!(r.level, NotifyLevel::Mentions);
}
#[test]
fn nothing_stored_anywhere_takes_what_the_conversation_is() {
let chat = resolve_from(ScopePrefs::default(), ScopePrefs::default(), NotifyLevel::All, 0);
assert_eq!(chat.level, NotifyLevel::All);
assert!(!chat.muted);
let community = resolve_from(ScopePrefs::default(), ScopePrefs::default(), NotifyLevel::Mentions, 0);
assert_eq!(community.ring, NotifyLevel::Mentions);
}
#[test]
fn any_stored_opinion_beats_the_default() {
let own = resolve_from(at(Some(NotifyLevel::All), 0), ScopePrefs::default(), NotifyLevel::Mentions, 0);
assert_eq!(own.level, NotifyLevel::All);
let inherited = resolve_from(ScopePrefs::default(), at(Some(NotifyLevel::All), 0), NotifyLevel::Mentions, 0);
assert_eq!(inherited.level, NotifyLevel::All, "a community set to All keeps its channels loud");
}
#[test]
fn a_community_mute_reaches_a_channel_that_set_none_itself() {
let r = resolve_from(at(Some(NotifyLevel::All), MUTE_OFF), at(None, MUTE_FOREVER), NotifyLevel::All, 0);
assert!(r.muted);
assert_eq!(r.level, NotifyLevel::All, "the level underneath is untouched");
assert_eq!(r.ring, NotifyLevel::Mentions, "but the mute clamps what rings");
}
#[test]
fn a_mute_never_makes_a_quiet_channel_louder() {
let r = resolve_from(at(Some(NotifyLevel::Nothing), MUTE_FOREVER), ScopePrefs::default(), NotifyLevel::All, 0);
assert_eq!(r.ring, NotifyLevel::Nothing);
}
#[test]
fn a_lapsed_timer_stops_muting_without_anything_being_written() {
let prefs = at(None, 5_000);
assert!(resolve_from(prefs, ScopePrefs::default(), NotifyLevel::All, 4_999).muted);
assert!(!resolve_from(prefs, ScopePrefs::default(), NotifyLevel::All, 5_000).muted);
}
#[test]
fn the_legacy_list_names_a_channel_its_community_muted() {
let channel = in_legacy_mute_list(ScopePrefs::default(), at(None, MUTE_FOREVER), 0);
assert!(channel);
}
#[test]
fn publishing_and_applying_the_legacy_list_agree() {
let community = at(None, MUTE_FOREVER);
let channel = ScopePrefs::default();
let published = in_legacy_mute_list(channel, community, 0);
let on_apply = in_legacy_mute_list(channel, community, 0);
assert_eq!(published, on_apply, "the applier must read what the publisher wrote");
assert!(published);
}
#[test]
fn a_timed_mute_never_enters_the_legacy_list() {
assert!(!in_legacy_mute_list(at(None, 9_000), ScopePrefs::default(), 0));
assert!(!in_legacy_mute_list(ScopePrefs::default(), at(None, 9_000), 0));
assert!(in_legacy_mute_list(at(None, MUTE_FOREVER), ScopePrefs::default(), 0));
}
#[test]
fn a_lapsed_indefinite_free_scope_leaves_the_legacy_list() {
let expired = at(None, 5_000);
assert!(!in_legacy_mute_list(expired, ScopePrefs::default(), 6_000));
}
#[test]
fn sweep_picks_exactly_the_timers_that_have_arrived() {
let lapsed = |until: i64, now: i64| until > MUTE_OFF && until <= now;
assert!(!lapsed(MUTE_FOREVER, 10_000), "indefinite never lapses");
assert!(!lapsed(MUTE_OFF, 10_000), "unmuted has no timer");
assert!(lapsed(10_000, 10_000), "an expiry that has arrived is over");
assert!(!lapsed(10_001, 10_000));
}
#[test]
fn scope_prefs_round_trip_through_the_wire_shape() {
let prefs = ScopePrefs {
level: Some(NotifyLevel::Mentions),
mute_until: 1_700_000_000_000,
suppress_everyone: Some(true),
};
assert_eq!(ScopePrefs::from_wire(&prefs.to_wire()), prefs);
assert!(ScopePrefs::from_wire(&crate::synced_prefs::NotifyEntry::default()).is_default());
}
#[test]
fn level_round_trips_through_both_wire_forms() {
for level in [NotifyLevel::All, NotifyLevel::Mentions, NotifyLevel::Nothing] {
assert_eq!(NotifyLevel::from_u8(level.as_u8()), Some(level));
assert_eq!(NotifyLevel::from_label(level.as_str()), Some(level));
}
assert_eq!(NotifyLevel::from_label("none"), Some(NotifyLevel::Nothing));
assert_eq!(NotifyLevel::from_label("whatever"), None);
assert_eq!(NotifyLevel::from_u8(9), None);
}
}