weirdnet-songnotes 0.5.0

SongNotes collaboration: the roles, permissions, links and consent requests for a SongNotes session, built on weirdnet-collab.
Documentation
//! The facade an app uses: one session as seen from this node.
use crate::link::JoinLink;
use crate::perm;
use crate::roles::{self, roles};
use weirdnet_collab::{
    Approval, Ctx, Decision, Duration, Explained, GrantStreams, Invite, InviteSpec, Permission, Project, ProjectId, Redeemed, RoleId, StreamId,
};
use weirdnet_contacts::UserId;
use weirdnet_net::Keypair;

const DAY_MS: i64 = 86_400_000;

/// Why a session call failed.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum SessionError {
    /// The permission model refused or the record was bad.
    #[error("{0}")]
    Collab(#[from] weirdnet_collab::Error),
    /// The link is for another project.
    #[error("the link is for another project")]
    WrongProject,
    /// The request was already answered or is not for this owner.
    #[error("not your consent to give")]
    NotYours,
}

/// What happened to someone who used a link.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Joined {
    /// They are in, with this role.
    Member(RoleId),
    /// They wait for the host to approve.
    Pending,
}

/// A question to an audio owner: may this person record or connect to your audio?
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ConsentRequest {
    /// The project.
    pub project: ProjectId,
    /// Who asks.
    pub requester: UserId,
    /// Whose audio it is, and so who must answer.
    pub owner: UserId,
    /// What they want to do.
    pub permission: Permission,
    /// The stream, if the request names one.
    pub stream: Option<StreamId>,
}

impl ConsentRequest {
    /// A line for the owner's prompt. `requester_name` is how the owner knows them.
    pub fn message(&self, requester_name: &str) -> String {
        let what = match self.permission.as_str() {
            perm::STREAM_RECORD => "record your audio",
            perm::MIC_RECORD => "record your talkback",
            perm::ROUTE_CONNECT => "connect to your audio",
            _ => "use your audio",
        };
        match &self.stream {
            Some(s) => format!("{requester_name} wants to {what} ({s})"),
            None => format!("{requester_name} wants to {what}"),
        }
    }
}

/// One session as seen from this node: a project, and the key this node signs with.
#[derive(Clone)]
pub struct Session {
    project: Project,
    me: Keypair,
}

impl Session {
    /// Start a session this node hosts.
    pub fn host(id: &str, me: Keypair, now: i64) -> Result<Session, SessionError> {
        let project = Project::new(id, &me, roles(), now)?;
        Ok(Session { project, me })
    }

    /// Standalone host mode: one session, one host, new people join as Viewers after the host
    /// approves them. Same as [`Session::host`]; use [`Session::quick_link`] to share it.
    pub fn standalone(id: &str, me: Keypair, now: i64) -> Result<Session, SessionError> {
        Session::host(id, me, now)
    }

    /// Pick up a session saved earlier, or a copy of one this node joined. `me` is this node's
    /// key: the host's key on the host, a member's own key on theirs. The project keeps its own
    /// role table, so a project saved by an older build keeps the roles it had.
    pub fn resume(project: Project, me: Keypair) -> Session {
        Session { project, me }
    }

    /// The project, to save it; [`Session::resume`] picks it up again.
    pub fn into_project(self) -> Project {
        self.project
    }

    /// The project.
    pub fn project(&self) -> &Project {
        &self.project
    }

    /// The project, to apply records that arrive from other nodes.
    pub fn project_mut(&mut self) -> &mut Project {
        &mut self.project
    }

    /// This node's user id.
    pub fn me(&self) -> UserId {
        UserId::of_keypair(&self.me)
    }

    /// A link for `role` that works for `ttl_ms` and, if given, `max_uses` people. It names this
    /// node as the host; add dial hints with [`JoinLink::with_addrs`].
    pub fn share_link(&mut self, role: &str, ttl_ms: i64, max_uses: Option<u32>, approval: Approval, now: i64) -> Result<JoinLink, SessionError> {
        let spec = InviteSpec { role: RoleId::new(role), to: None, expires_ms: now + ttl_ms, max_uses, approval };
        let inv = self.project.create_invite(&self.me, spec, now)?;
        Ok(JoinLink::new(self.project.id().clone(), inv.id).with_host(self.me()))
    }

    /// The standalone default: a Viewer link for a day, the host approves each person.
    pub fn quick_link(&mut self, now: i64) -> Result<JoinLink, SessionError> {
        self.share_link(roles::VIEWER, DAY_MS, None, Approval::HostApproves, now)
    }

    /// A direct invite to one identity (a contact).
    pub fn invite_contact(&mut self, user: &UserId, role: &str, ttl_ms: i64, now: i64) -> Result<Invite, SessionError> {
        let spec =
            InviteSpec { role: RoleId::new(role), to: Some(user.clone()), expires_ms: now + ttl_ms, max_uses: Some(1), approval: Approval::Auto };
        Ok(self.project.create_invite(&self.me, spec, now)?)
    }

    /// Someone used a link. The host node decides: in, or waiting for approval.
    pub fn join(&mut self, link: &JoinLink, user: &UserId, now: i64) -> Result<Joined, SessionError> {
        if &link.project != self.project.id() {
            return Err(SessionError::WrongProject);
        }
        Ok(match self.project.redeem(&self.me, &link.invite, user, now)? {
            Redeemed::Joined(role) => Joined::Member(role),
            Redeemed::Pending => Joined::Pending,
        })
    }

    /// People waiting for approval.
    pub fn pending(&self) -> Vec<UserId> {
        self.project.pending().iter().map(|r| r.user.clone()).collect()
    }

    /// Let a waiting person in.
    pub fn approve(&mut self, user: &UserId, now: i64) -> Result<(), SessionError> {
        Ok(self.project.approve(&self.me, user, now)?)
    }

    /// Turn a waiting person away.
    pub fn deny(&mut self, user: &UserId, now: i64) -> Result<(), SessionError> {
        Ok(self.project.deny(&self.me, user, now)?)
    }

    /// May `who` do `permission`? Gated permissions on someone's audio need
    /// [`Session::can_audio`].
    pub fn can(&self, who: &UserId, permission: &str, now: i64) -> bool {
        self.project.can(who, permission, &Ctx::at(now))
    }

    /// The decision for `who` and `permission` with the steps that led to it.
    pub fn explain(&self, who: &UserId, permission: &str, now: i64) -> Explained {
        self.project.decide(who, &Permission::new(permission), &Ctx::at(now))
    }

    /// May `who` do `permission` to `owner`'s audio (optionally one stream)?
    pub fn can_audio(&self, who: &UserId, permission: &str, owner: &UserId, stream: Option<&str>, now: i64) -> Explained {
        self.project.decide(who, &Permission::new(permission), &Ctx::at(now).audio(owner, stream))
    }

    /// If `who` would need `owner`'s consent for this, the request to put to `owner`.
    pub fn consent_request(&self, who: &UserId, permission: &str, owner: &UserId, stream: Option<&str>, now: i64) -> Option<ConsentRequest> {
        match self.can_audio(who, permission, owner, stream, now).decision {
            Decision::NeedsConsent { owner } => Some(ConsentRequest {
                project: self.project.id().clone(),
                requester: who.clone(),
                owner,
                permission: Permission::new(permission),
                stream: stream.map(StreamId::new),
            }),
            _ => None,
        }
    }

    /// The owner says yes. `owner_key` must be the owner's own key; the grant covers the
    /// requester and the request's stream (all of the owner's streams if it named none).
    pub fn grant(&mut self, owner_key: &Keypair, req: &ConsentRequest, how: Duration, now: i64) -> Result<(), SessionError> {
        if UserId::of_keypair(owner_key) != req.owner || &req.project != self.project.id() {
            return Err(SessionError::NotYours);
        }
        let streams = match &req.stream {
            Some(s) => GrantStreams::Only(vec![s.clone()]),
            None => GrantStreams::All,
        };
        self.project.grant_consent(owner_key, &req.requester, req.permission.as_str(), streams, how, now)?;
        Ok(())
    }
}