Skip to main content

weirdnet_songnotes/
session.rs

1//! The facade an app uses: one session as seen from this node.
2use crate::link::JoinLink;
3use crate::perm;
4use crate::roles::{self, roles};
5use weirdnet_collab::{
6    Approval, Ctx, Decision, Duration, Explained, GrantStreams, Handover, HandoverKind, Invite, InviteSpec, Permission, Project, ProjectId, Redeemed,
7    RoleId, StreamId,
8};
9use weirdnet_contacts::UserId;
10use weirdnet_net::Keypair;
11
12const DAY_MS: i64 = 86_400_000;
13
14/// Why a session call failed.
15#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
16pub enum SessionError {
17    /// The permission model refused or the record was bad.
18    #[error("{0}")]
19    Collab(#[from] weirdnet_collab::Error),
20    /// The link is for another project.
21    #[error("the link is for another project")]
22    WrongProject,
23    /// The request was already answered or is not for this owner.
24    #[error("not your consent to give")]
25    NotYours,
26}
27
28/// What happened to someone who used a link.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub enum Joined {
31    /// They are in, with this role.
32    Member(RoleId),
33    /// They wait for the host to approve.
34    Pending,
35}
36
37/// A question to an audio owner: may this person record or connect to your audio?
38#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
39pub struct ConsentRequest {
40    /// The project.
41    pub project: ProjectId,
42    /// Who asks.
43    pub requester: UserId,
44    /// Whose audio it is, and so who must answer.
45    pub owner: UserId,
46    /// What they want to do.
47    pub permission: Permission,
48    /// The stream, if the request names one.
49    pub stream: Option<StreamId>,
50}
51
52impl ConsentRequest {
53    /// A line for the owner's prompt. `requester_name` is how the owner knows them.
54    pub fn message(&self, requester_name: &str) -> String {
55        let what = match self.permission.as_str() {
56            perm::STREAM_RECORD => "record your audio",
57            perm::MIC_RECORD => "record your talkback",
58            perm::ROUTE_CONNECT => "connect to your audio",
59            _ => "use your audio",
60        };
61        match &self.stream {
62            Some(s) => format!("{requester_name} wants to {what} ({s})"),
63            None => format!("{requester_name} wants to {what}"),
64        }
65    }
66}
67
68/// One session as seen from this node: a project, and the key this node signs with.
69#[derive(Clone)]
70pub struct Session {
71    project: Project,
72    me: Keypair,
73}
74
75impl Session {
76    /// Start a session this node hosts.
77    pub fn host(id: &str, me: Keypair, now: i64) -> Result<Session, SessionError> {
78        let project = Project::new(id, &me, roles(), now)?;
79        Ok(Session { project, me })
80    }
81
82    /// Standalone host mode: one session, one host, new people join as Viewers after the host
83    /// approves them. Same as [`Session::host`]; use [`Session::quick_link`] to share it.
84    pub fn standalone(id: &str, me: Keypair, now: i64) -> Result<Session, SessionError> {
85        Session::host(id, me, now)
86    }
87
88    /// Pick up a session saved earlier, or a copy of one this node joined. `me` is this node's
89    /// key: the host's key on the host, a member's own key on theirs. The project keeps its own
90    /// role table, so a project saved by an older build keeps the roles it had.
91    pub fn resume(project: Project, me: Keypair) -> Session {
92        Session { project, me }
93    }
94
95    /// The project, to save it; [`Session::resume`] picks it up again.
96    pub fn into_project(self) -> Project {
97        self.project
98    }
99
100    /// The project.
101    pub fn project(&self) -> &Project {
102        &self.project
103    }
104
105    /// The project, to apply records that arrive from other nodes.
106    pub fn project_mut(&mut self) -> &mut Project {
107        &mut self.project
108    }
109
110    /// This node's user id.
111    pub fn me(&self) -> UserId {
112        UserId::of_keypair(&self.me)
113    }
114
115    /// A link for `role` that works for `ttl_ms` and, if given, `max_uses` people. It names this
116    /// node as the host; add dial hints with [`JoinLink::with_addrs`].
117    pub fn share_link(&mut self, role: &str, ttl_ms: i64, max_uses: Option<u32>, approval: Approval, now: i64) -> Result<JoinLink, SessionError> {
118        let spec = InviteSpec { role: RoleId::new(role), to: None, expires_ms: now + ttl_ms, max_uses, approval };
119        let inv = self.project.create_invite(&self.me, spec, now)?;
120        Ok(JoinLink::new(self.project.id().clone(), inv.id).with_host(self.me()))
121    }
122
123    /// The standalone default: a Viewer link for a day, the host approves each person.
124    pub fn quick_link(&mut self, now: i64) -> Result<JoinLink, SessionError> {
125        self.share_link(roles::VIEWER, DAY_MS, None, Approval::HostApproves, now)
126    }
127
128    /// A direct invite to one identity (a contact).
129    pub fn invite_contact(&mut self, user: &UserId, role: &str, ttl_ms: i64, now: i64) -> Result<Invite, SessionError> {
130        let spec =
131            InviteSpec { role: RoleId::new(role), to: Some(user.clone()), expires_ms: now + ttl_ms, max_uses: Some(1), approval: Approval::Auto };
132        Ok(self.project.create_invite(&self.me, spec, now)?)
133    }
134
135    /// Someone used a link. The host node decides: in, or waiting for approval.
136    pub fn join(&mut self, link: &JoinLink, user: &UserId, now: i64) -> Result<Joined, SessionError> {
137        if &link.project != self.project.id() {
138            return Err(SessionError::WrongProject);
139        }
140        Ok(match self.project.redeem(&self.me, &link.invite, user, now)? {
141            Redeemed::Joined(role) => Joined::Member(role),
142            Redeemed::Pending => Joined::Pending,
143        })
144    }
145
146    /// Remove a member (needs `session.manage`).
147    pub fn kick(&mut self, user: &UserId, now: i64) -> Result<(), SessionError> {
148        Ok(self.project.kick(&self.me, user, now)?)
149    }
150
151    /// Ban an identity from the session (needs `session.manage`).
152    pub fn ban(&mut self, user: &UserId, now: i64) -> Result<(), SessionError> {
153        Ok(self.project.ban(&self.me, user, now)?)
154    }
155
156    /// As host, sign a handover of the host role to the member `to`.
157    pub fn hand_over(&self, to: &UserId, kind: HandoverKind, now: i64) -> Result<Handover, SessionError> {
158        Ok(self.project.hand_over(&self.me, to, kind, now)?)
159    }
160
161    /// Become host of this copy of the session with a handover the host signed to you.
162    pub fn accept_handover(&mut self, h: &Handover, now: i64) -> Result<(), SessionError> {
163        Ok(self.project.accept_handover(&self.me, h, now)?)
164    }
165
166    /// People waiting for approval.
167    pub fn pending(&self) -> Vec<UserId> {
168        self.project.pending().iter().map(|r| r.user.clone()).collect()
169    }
170
171    /// Let a waiting person in.
172    pub fn approve(&mut self, user: &UserId, now: i64) -> Result<(), SessionError> {
173        Ok(self.project.approve(&self.me, user, now)?)
174    }
175
176    /// Turn a waiting person away.
177    pub fn deny(&mut self, user: &UserId, now: i64) -> Result<(), SessionError> {
178        Ok(self.project.deny(&self.me, user, now)?)
179    }
180
181    /// May `who` do `permission`? Gated permissions on someone's audio need
182    /// [`Session::can_audio`].
183    pub fn can(&self, who: &UserId, permission: &str, now: i64) -> bool {
184        self.project.can(who, permission, &Ctx::at(now))
185    }
186
187    /// The decision for `who` and `permission` with the steps that led to it.
188    pub fn explain(&self, who: &UserId, permission: &str, now: i64) -> Explained {
189        self.project.decide(who, &Permission::new(permission), &Ctx::at(now))
190    }
191
192    /// May `who` do `permission` to `owner`'s audio (optionally one stream)?
193    pub fn can_audio(&self, who: &UserId, permission: &str, owner: &UserId, stream: Option<&str>, now: i64) -> Explained {
194        self.project.decide(who, &Permission::new(permission), &Ctx::at(now).audio(owner, stream))
195    }
196
197    /// If `who` would need `owner`'s consent for this, the request to put to `owner`.
198    pub fn consent_request(&self, who: &UserId, permission: &str, owner: &UserId, stream: Option<&str>, now: i64) -> Option<ConsentRequest> {
199        match self.can_audio(who, permission, owner, stream, now).decision {
200            Decision::NeedsConsent { owner } => Some(ConsentRequest {
201                project: self.project.id().clone(),
202                requester: who.clone(),
203                owner,
204                permission: Permission::new(permission),
205                stream: stream.map(StreamId::new),
206            }),
207            _ => None,
208        }
209    }
210
211    /// The owner says yes. `owner_key` must be the owner's own key; the grant covers the
212    /// requester and the request's stream (all of the owner's streams if it named none).
213    pub fn grant(&mut self, owner_key: &Keypair, req: &ConsentRequest, how: Duration, now: i64) -> Result<(), SessionError> {
214        if UserId::of_keypair(owner_key) != req.owner || &req.project != self.project.id() {
215            return Err(SessionError::NotYours);
216        }
217        let streams = match &req.stream {
218            Some(s) => GrantStreams::Only(vec![s.clone()]),
219            None => GrantStreams::All,
220        };
221        self.project.grant_consent(owner_key, &req.requester, req.permission.as_str(), streams, how, now)?;
222        Ok(())
223    }
224}