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
//! Talking to another node's contacts service.
use crate::contacts::{Contacts, Receipt, now_ms};
use crate::id::UserId;
use crate::message::Delivery;
use crate::presence::PresenceView;
use crate::service::{Req, Resp, protocol};
use weirdnet_service::{Client, ServiceError, Session};

/// A session with `peer`'s contacts service. The client must be able to dial it (see
/// `weirdnet_service::net::NetDialer::hint`).
pub async fn open_session(client: &Client, peer: &UserId) -> Result<Session<Req, Resp>, ServiceError> {
    client.session::<Req, Resp>(peer.as_str(), &protocol()).await
}

/// Send every queued message to `peer`. A delivered message becomes `Delivered`; one the
/// other side refuses (blocked, rate limited, ...) becomes `Failed` and stays out of the
/// outbox until [`Contacts::retry_failed`]; a broken connection stops the flush and leaves
/// the rest queued. Returns how many were delivered.
pub async fn flush(contacts: &Contacts, session: &Session<Req, Resp>, peer: &UserId) -> Result<usize, ServiceError> {
    let mut sent = 0;
    for m in contacts.outbox(peer) {
        let id = m.id.clone();
        match session.call(&Req::Deliver(m)).await {
            Ok(Resp::Ack(Receipt::Delivered | Receipt::Request | Receipt::Duplicate)) => {
                contacts.mark(peer, &id, Delivery::Delivered);
                sent += 1;
            }
            Ok(_) => contacts.mark(peer, &id, Delivery::Failed),
            Err(ServiceError::App { .. } | ServiceError::Refused { .. } | ServiceError::BadRequest { .. }) => {
                contacts.mark(peer, &id, Delivery::Failed)
            }
            Err(e) => {
                contacts.mark(peer, &id, Delivery::Sent);
                return Err(e);
            }
        }
    }
    Ok(sent)
}

/// Ask `peer` for the messages they wrote to you since the newest you hold, and take them in.
/// Returns how many were new.
pub async fn pull(contacts: &Contacts, session: &Session<Req, Resp>, peer: &UserId) -> Result<usize, ServiceError> {
    let since = contacts.newest_from(peer);
    let Resp::Messages(msgs) = session.call(&Req::Pull { since_ms: since }).await? else {
        return Err(ServiceError::App { code: "bad-response".into(), message: "not messages".into() });
    };
    let now = now_ms();
    Ok(msgs
        .into_iter()
        .filter(|m| &m.from == peer)
        .filter(|m| matches!(contacts.receive(m.clone(), now), Ok(Receipt::Delivered | Receipt::Request)))
        .count())
}

/// What `peer` shows you of their presence (`None`: they blocked you).
pub async fn presence(session: &Session<Req, Resp>) -> Result<Option<PresenceView>, ServiceError> {
    match session.call(&Req::Presence).await? {
        Resp::Presence(p) => Ok(p),
        _ => Err(ServiceError::App { code: "bad-response".into(), message: "not presence".into() }),
    }
}

/// Mark everything from `peer` read and tell them. Returns how many messages were newly read.
pub async fn send_read(contacts: &Contacts, session: &Session<Req, Resp>, peer: &UserId) -> Result<usize, ServiceError> {
    let ids = contacts.mark_read(peer);
    if ids.is_empty() {
        return Ok(0);
    }
    let n = ids.len();
    session.call(&Req::Read { ids }).await?;
    Ok(n)
}