weirdnet-contacts 0.1.0

A contact book for Weirdnet apps: trusted and blocked identities, presence with privacy rules (base to everyone, detail to trusted contacts), signed text direct messages with delivery state and an offline queue, and contact links, served over weirdnet-service.
Documentation
//! The contact book: who is trusted, who is blocked, who is banned, and your presence policy.
use crate::id::UserId;
use crate::presence::{Audience, PresencePolicy};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};

/// How you treat an identity.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ContactState {
    /// Not in the book, or added without trust (someone who wrote first).
    Unknown,
    /// Sees your detail presence and can write without being a request.
    Trusted,
    /// Refused everywhere: no messages, no invites, no presence.
    Blocked,
}

/// One entry.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Contact {
    /// The identity.
    pub user: UserId,
    /// A local label you can edit.
    pub name: String,
    /// How you treat them.
    pub state: ContactState,
    /// When the entry was made, milliseconds since the epoch.
    pub since_ms: i64,
    /// When `state` or `name` last changed; the newer entry wins in [`Book::merge`].
    pub changed_ms: i64,
    /// Overrides [`PresencePolicy::detail`] for this contact.
    pub audience: Option<Audience>,
}

/// The book. Serializable; the app stores it.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Book {
    contacts: BTreeMap<UserId, Contact>,
    bans: BTreeSet<UserId>,
    /// What your presence shows to whom.
    pub policy: PresencePolicy,
}

impl Book {
    /// An empty book with the default policy.
    pub fn new() -> Self {
        Self::default()
    }

    /// The entry for `user`.
    pub fn get(&self, user: &UserId) -> Option<&Contact> {
        self.contacts.get(user)
    }

    /// How `user` is treated (`Unknown` when not in the book). A banned identity reads as
    /// `Blocked`.
    pub fn state_of(&self, user: &UserId) -> ContactState {
        if self.bans.contains(user) {
            return ContactState::Blocked;
        }
        self.contacts.get(user).map_or(ContactState::Unknown, |c| c.state)
    }

    /// All entries by identity.
    pub fn list(&self) -> impl Iterator<Item = &Contact> {
        self.contacts.values()
    }

    /// Whether `user` is on the ban list (a host's or your own ban, keyed by identity).
    pub fn is_banned(&self, user: &UserId) -> bool {
        self.bans.contains(user)
    }

    fn entry(&mut self, user: &UserId, name: &str, now: i64) -> &mut Contact {
        self.contacts.entry(user.clone()).or_insert_with(|| Contact {
            user: user.clone(),
            name: name.to_string(),
            state: ContactState::Unknown,
            since_ms: now,
            changed_ms: now,
            audience: None,
        })
    }

    /// Add `user` (or update their name) and trust them. A blocked identity becomes trusted
    /// too: adding is a deliberate act.
    pub fn trust(&mut self, user: &UserId, name: &str, now: i64) {
        let c = self.entry(user, name, now);
        if !name.is_empty() {
            c.name = name.to_string();
        }
        c.state = ContactState::Trusted;
        c.changed_ms = now;
    }

    /// Note an identity without trusting it (what an unknown sender becomes).
    pub fn note(&mut self, user: &UserId, name: &str, now: i64) {
        self.entry(user, name, now);
    }

    /// Block `user`.
    pub fn block(&mut self, user: &UserId, now: i64) {
        let c = self.entry(user, "", now);
        c.state = ContactState::Blocked;
        c.changed_ms = now;
    }

    /// Lift a block: the identity goes back to `Unknown`. Not a way back to trusted.
    pub fn unblock(&mut self, user: &UserId, now: i64) {
        if let Some(c) = self.contacts.get_mut(user)
            && c.state == ContactState::Blocked
        {
            c.state = ContactState::Unknown;
            c.changed_ms = now;
        }
    }

    /// Forget `user` entirely (a trusted contact you remove is `Unknown` again).
    pub fn remove(&mut self, user: &UserId) -> bool {
        self.contacts.remove(user).is_some()
    }

    /// Rename a contact locally.
    pub fn rename(&mut self, user: &UserId, name: &str, now: i64) {
        if let Some(c) = self.contacts.get_mut(user) {
            c.name = name.to_string();
            c.changed_ms = now;
        }
    }

    /// Set or clear the detail audience for one contact.
    pub fn set_audience(&mut self, user: &UserId, audience: Option<Audience>, now: i64) {
        if let Some(c) = self.contacts.get_mut(user) {
            c.audience = audience;
            c.changed_ms = now;
        }
    }

    /// Put `user` on the ban list: refused like a block, and a later `unblock` or `trust` does
    /// not lift it. Bans are for a host or an operator; `unban` lifts one.
    pub fn ban(&mut self, user: &UserId) {
        self.bans.insert(user.clone());
    }

    /// Lift a ban.
    pub fn unban(&mut self, user: &UserId) {
        self.bans.remove(user);
    }

    /// Fold in another copy of the book (your own device's): per identity the entry changed
    /// last wins, bans are added, and the policy of the copy that changed last is not guessed:
    /// ours stays. A removal on one device is not carried (it would need a tombstone).
    pub fn merge(&mut self, other: &Book) {
        for (u, c) in &other.contacts {
            match self.contacts.get(u) {
                Some(mine) if mine.changed_ms >= c.changed_ms => {}
                _ => {
                    self.contacts.insert(u.clone(), c.clone());
                }
            }
        }
        self.bans.extend(other.bans.iter().cloned());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use weirdnet_net::Keypair;

    fn u() -> UserId {
        UserId::of_keypair(&Keypair::generate_ed25519())
    }

    #[test]
    fn states_follow_the_book() {
        let mut b = Book::new();
        let (a, c) = (u(), u());
        assert_eq!(b.state_of(&a), ContactState::Unknown);
        b.trust(&a, "Ana", 1);
        assert_eq!(b.state_of(&a), ContactState::Trusted);
        b.block(&a, 2);
        assert_eq!(b.state_of(&a), ContactState::Blocked);
        b.unblock(&a, 3);
        assert_eq!(b.state_of(&a), ContactState::Unknown, "unblock is not trust");
        b.block(&c, 4);
        b.trust(&c, "Cy", 5);
        assert_eq!(b.state_of(&c), ContactState::Trusted, "adding is deliberate");
        assert_eq!(b.get(&c).unwrap().name, "Cy");
        assert!(b.remove(&c));
        assert_eq!(b.state_of(&c), ContactState::Unknown);
    }

    #[test]
    fn a_ban_outlives_trust_and_unblock() {
        let mut b = Book::new();
        let a = u();
        b.trust(&a, "Ana", 1);
        b.ban(&a);
        assert_eq!(b.state_of(&a), ContactState::Blocked);
        b.trust(&a, "Ana", 2);
        b.unblock(&a, 3);
        assert_eq!(b.state_of(&a), ContactState::Blocked);
        assert!(b.is_banned(&a));
        b.unban(&a);
        assert_eq!(b.state_of(&a), ContactState::Trusted);
    }

    #[test]
    fn merge_takes_the_newer_entry_and_all_bans() {
        let (a, c) = (u(), u());
        let mut one = Book::new();
        one.trust(&a, "Ana", 10);
        let mut two = Book::new();
        two.block(&a, 20);
        two.trust(&c, "Cy", 5);
        two.ban(&c);
        one.merge(&two);
        assert_eq!(one.state_of(&a), ContactState::Blocked, "newer change wins");
        assert!(one.is_banned(&c));
        let mut stale = Book::new();
        stale.trust(&a, "Ana", 15);
        one.merge(&stale);
        assert_eq!(one.state_of(&a), ContactState::Blocked, "older change loses");
    }

    #[test]
    fn the_book_round_trips_through_serde() {
        let mut b = Book::new();
        b.trust(&u(), "Ana", 1);
        b.ban(&u());
        let s = serde_json::to_string(&b).unwrap();
        assert_eq!(serde_json::from_str::<Book>(&s).unwrap(), b);
    }
}