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
//! Presence and who may see what.
//!
//! Base presence (online, away or busy) is for everyone online. The detail fields, a status
//! line, an in-session hint and last seen, go only to the audience your [`PresencePolicy`]
//! names (trusted contacts by default), and only the fields the policy shares. A blocked
//! viewer sees nothing, and an invisible identity looks offline to everyone.
use crate::book::ContactState;
use serde::{Deserialize, Serialize};

/// A presence state.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Presence {
    /// Here and available.
    Online,
    /// Here, not paying attention.
    Away,
    /// Here, do not disturb.
    Busy,
    /// Online but not shown: everyone else sees `Offline`.
    Invisible,
    /// Not here (also what an invisible identity shows).
    Offline,
}

/// What an identity says about being in a session.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum SessionHint {
    /// Nothing.
    Hidden,
    /// Only that they are in a session.
    Anonymous,
    /// The project they are in.
    Named(String),
}

/// What you publish about yourself (never leaves your node whole: [`view_for`] cuts it).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PresenceInfo {
    /// Your state.
    pub state: Presence,
    /// A short status line.
    pub status: Option<String>,
    /// The session hint.
    pub in_session: SessionHint,
    /// When this was last updated, milliseconds since the epoch.
    pub updated_ms: i64,
}

impl Default for PresenceInfo {
    fn default() -> Self {
        PresenceInfo { state: Presence::Offline, status: None, in_session: SessionHint::Hidden, updated_ms: 0 }
    }
}

/// Who a thing is shown to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Audience {
    /// Everyone who is not blocked.
    Everyone,
    /// Trusted contacts.
    Trusted,
    /// Nobody.
    Nobody,
}

/// Your privacy settings for presence.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PresencePolicy {
    /// Who sees your base state. `Everyone` by default; `Nobody` is the same as invisible.
    pub base: Audience,
    /// Who sees the detail fields. `Trusted` by default.
    pub detail: Audience,
    /// Share last seen with the detail audience. Off by default.
    pub share_last_seen: bool,
    /// Share a named project with the detail audience when they are in it too. Off by default:
    /// the hint is then only "in a session".
    pub share_project_name: bool,
    /// Share the status line with the detail audience. On by default.
    pub share_status: bool,
}

impl Default for PresencePolicy {
    fn default() -> Self {
        PresencePolicy { base: Audience::Everyone, detail: Audience::Trusted, share_last_seen: false, share_project_name: false, share_status: true }
    }
}

/// The session hint as a viewer sees it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum InSession {
    /// In a session, unnamed.
    Anonymous,
    /// In this project.
    Project(String),
}

/// The detail fields a viewer may see.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Detail {
    /// The status line.
    pub status: Option<String>,
    /// The session hint.
    pub in_session: Option<InSession>,
    /// When they were last seen, milliseconds since the epoch.
    pub last_seen_ms: Option<i64>,
}

/// What one viewer sees.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PresenceView {
    /// The base state.
    pub state: Presence,
    /// The detail, if this viewer is in the detail audience and anything is shared.
    pub detail: Option<Detail>,
}

/// Who is looking.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Viewer {
    /// How you treat the viewer.
    pub state: ContactState,
    /// Whether the viewer is a member of the project the hint names.
    pub shares_project: bool,
    /// Overrides the policy's detail audience for this viewer.
    pub audience: Option<Audience>,
}

impl Viewer {
    /// A viewer with no override and no shared project.
    pub fn new(state: ContactState) -> Self {
        Viewer { state, shares_project: false, audience: None }
    }
}

/// What `viewer` may see of `info` under `policy`: `None` for a blocked viewer.
pub fn view_for(policy: &PresencePolicy, info: &PresenceInfo, viewer: Viewer) -> Option<PresenceView> {
    if viewer.state == ContactState::Blocked {
        return None;
    }
    let trusted = viewer.state == ContactState::Trusted;
    let hidden = info.state == Presence::Invisible || policy.base == Audience::Nobody || info.state == Presence::Offline;
    if hidden {
        return Some(PresenceView { state: Presence::Offline, detail: None });
    }
    let audience = viewer.audience.unwrap_or(policy.detail);
    let allowed = match audience {
        Audience::Everyone => true,
        Audience::Trusted => trusted,
        Audience::Nobody => false,
    };
    let detail = allowed.then(|| Detail {
        status: if policy.share_status { info.status.clone() } else { None },
        in_session: match &info.in_session {
            SessionHint::Hidden => None,
            SessionHint::Anonymous => Some(InSession::Anonymous),
            SessionHint::Named(p) if policy.share_project_name && viewer.shares_project => Some(InSession::Project(p.clone())),
            SessionHint::Named(_) => Some(InSession::Anonymous),
        },
        last_seen_ms: policy.share_last_seen.then_some(info.updated_ms),
    });
    let detail = detail.filter(|d| d.status.is_some() || d.in_session.is_some() || d.last_seen_ms.is_some());
    Some(PresenceView { state: info.state, detail })
}

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

    fn info() -> PresenceInfo {
        PresenceInfo { state: Presence::Busy, status: Some("mixing".into()), in_session: SessionHint::Named("Secret EP".into()), updated_ms: 777 }
    }

    fn see(p: &PresencePolicy, v: Viewer) -> Option<PresenceView> {
        view_for(p, &info(), v)
    }

    #[test]
    fn everyone_sees_base_and_only_trusted_see_detail() {
        let p = PresencePolicy::default();
        let stranger = see(&p, Viewer::new(ContactState::Unknown)).unwrap();
        assert_eq!(stranger, PresenceView { state: Presence::Busy, detail: None });
        let friend = see(&p, Viewer::new(ContactState::Trusted)).unwrap();
        let d = friend.detail.unwrap();
        assert_eq!(d.status.as_deref(), Some("mixing"));
        assert_eq!(d.in_session, Some(InSession::Anonymous), "the project name is off by default");
        assert_eq!(d.last_seen_ms, None, "last seen is off by default");
    }

    #[test]
    fn the_project_name_needs_the_policy_and_a_shared_project() {
        let p = PresencePolicy { share_project_name: true, share_last_seen: true, ..Default::default() };
        let mut v = Viewer::new(ContactState::Trusted);
        assert_eq!(see(&p, v).unwrap().detail.unwrap().in_session, Some(InSession::Anonymous));
        v.shares_project = true;
        let d = see(&p, v).unwrap().detail.unwrap();
        assert_eq!(d.in_session, Some(InSession::Project("Secret EP".into())));
        assert_eq!(d.last_seen_ms, Some(777));
    }

    #[test]
    fn blocked_sees_nothing_and_invisible_looks_offline() {
        let p = PresencePolicy::default();
        assert!(see(&p, Viewer::new(ContactState::Blocked)).is_none());
        let mut i = info();
        i.state = Presence::Invisible;
        for s in [ContactState::Trusted, ContactState::Unknown] {
            assert_eq!(view_for(&p, &i, Viewer::new(s)).unwrap(), PresenceView { state: Presence::Offline, detail: None });
        }
        let hidden = PresencePolicy { base: Audience::Nobody, ..Default::default() };
        assert_eq!(see(&hidden, Viewer::new(ContactState::Trusted)).unwrap().state, Presence::Offline);
    }

    #[test]
    fn audiences_and_per_contact_overrides() {
        let open = PresencePolicy { detail: Audience::Everyone, ..Default::default() };
        assert!(see(&open, Viewer::new(ContactState::Unknown)).unwrap().detail.is_some());
        let closed = PresencePolicy { detail: Audience::Nobody, ..Default::default() };
        assert!(see(&closed, Viewer::new(ContactState::Trusted)).unwrap().detail.is_none());
        let mut v = Viewer::new(ContactState::Trusted);
        v.audience = Some(Audience::Nobody);
        assert!(see(&PresencePolicy::default(), v).unwrap().detail.is_none(), "override hides from one contact");
        let mut v = Viewer::new(ContactState::Unknown);
        v.audience = Some(Audience::Everyone);
        assert!(see(&PresencePolicy::default(), v).unwrap().detail.is_some());
    }

    #[test]
    fn nothing_shared_means_no_detail() {
        let p = PresencePolicy { share_status: false, ..Default::default() };
        let mut i = info();
        i.in_session = SessionHint::Hidden;
        assert_eq!(view_for(&p, &i, Viewer::new(ContactState::Trusted)).unwrap().detail, None);
    }
}