use crate::session::ConsentRequest;
use serde::{Deserialize, Serialize};
use weirdnet_collab::{
AuditEntry, AuditKind, ChatItem, ChatMessage, ConsentGrant, Decision, Duration, Effect, Explained, GrantStreams, ProjectId, RecordId, Revocation,
RoleId, SignError, Step, StreamId,
};
use weirdnet_contacts::UserId;
use weirdnet_net::Keypair;
use weirdnet_service::ProtocolId;
pub const PROTOCOL: &str = "/songnotes/collab";
pub const VERSION: u32 = 1;
pub const RE_AUTH_MS: i64 = 5_000;
pub const PRESENCE_REFRESH_MS: i64 = 20_000;
pub const PRESENCE_TTL_MS: i64 = 60_000;
const _: () = assert!(RE_AUTH_MS < PRESENCE_REFRESH_MS && PRESENCE_REFRESH_MS < PRESENCE_TTL_MS);
pub fn protocol() -> ProtocolId {
ProtocolId::new(PROTOCOL, VERSION).expect("a valid protocol id")
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Standing {
Member(RoleId),
Pending,
Out,
Banned,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Activity {
Active,
Idle,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Here {
pub app: String,
pub activity: Activity,
pub at_ms: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub peer: Option<String>,
}
pub const PEER_PERMISSIONS: &[&str] = &[crate::perm::ROUTE_CONNECT];
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerRight {
pub peer: String,
pub user: UserId,
pub app: String,
pub right: Explained,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Person {
pub user: UserId,
pub role: RoleId,
pub apps: Vec<Here>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectView {
pub project: ProjectId,
pub title: String,
pub host: UserId,
pub standing: Standing,
pub people: Vec<Person>,
pub audit: Vec<AuditEntry>,
#[serde(default)]
pub consent_requests: Vec<ConsentRequest>,
#[serde(default)]
pub grants: Vec<ConsentGrant>,
#[serde(default)]
pub rights: Vec<Explained>,
pub at_ms: i64,
}
impl ProjectView {
pub fn person(&self, user: &UserId) -> Option<&Person> {
self.people.iter().find(|p| &p.user == user)
}
pub fn right(&self, permission: &str) -> Option<&Explained> {
self.rights.iter().find(|e| e.permission.as_str() == permission)
}
pub fn audit_verifies(&self) -> bool {
self.audit.iter().all(AuditEntry::verify)
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Req {
Join {
link: String,
},
Status {
project: ProjectId,
},
Sync {
project: ProjectId,
},
Here {
project: ProjectId,
app: String,
activity: Activity,
#[serde(default, skip_serializing_if = "Option::is_none")]
peer: Option<String>,
},
Peers {
project: ProjectId,
permission: String,
},
Can {
project: ProjectId,
permission: String,
owner: Option<UserId>,
stream: Option<String>,
act: bool,
},
Grant {
grant: ConsentGrant,
#[serde(default)]
entry: Option<AuditEntry>,
},
Revoke {
revocation: Revocation,
#[serde(default)]
entry: Option<AuditEntry>,
},
Decline {
request: ConsentRequest,
},
Say {
message: ChatMessage,
},
React {
project: ProjectId,
message: RecordId,
reaction: String,
on: bool,
},
Unsay {
project: ProjectId,
message: RecordId,
},
Chat {
project: ProjectId,
since: u64,
},
Cert {
project: ProjectId,
},
Talk {
project: ProjectId,
},
Mic {
project: ProjectId,
peer: String,
addrs: Vec<String>,
stream: String,
live: bool,
},
MuteMic {
project: ProjectId,
user: Option<UserId>,
muted: bool,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Answer {
pub project: ProjectId,
pub title: Option<String>,
pub standing: Standing,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChatPage {
pub items: Vec<ChatItem>,
pub seq: u64,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Resp {
Answer(Answer),
View(Box<ProjectView>),
Noted,
Decision(Box<Explained>),
Seq(u64),
Chat(ChatPage),
Cert(Box<crate::stage::Cert>),
Talk(Box<crate::talk::TalkState>),
Peers(Vec<PeerRight>),
}
pub fn audit_line(e: &AuditEntry, name: impl Fn(&UserId) -> String) -> String {
let by = name(&e.by);
match &e.kind {
AuditKind::RuleSet { permission, effect, member, role, .. } => {
let who = member.as_ref().map(&name).or_else(|| role.as_ref().map(|r| format!("every {r}"))).unwrap_or_else(|| "everyone".into());
let verb = if matches!(effect, weirdnet_collab::Effect::Allow) { "allowed" } else { "denied" };
format!("{by} {verb} {permission} for {who}")
}
AuditKind::RuleRemoved { .. } => format!("{by} removed a rule"),
AuditKind::RoleChanged { user, from, to } => format!("{by} changed {} from {from} to {to}", name(user)),
AuditKind::MemberJoined { user, role, .. } => format!("{} joined as {role}", name(user)),
AuditKind::MemberKicked { user } => format!("{by} removed {}", name(user)),
AuditKind::MemberBanned { user } => format!("{by} banned {}", name(user)),
AuditKind::MemberUnbanned { user } => format!("{by} lifted the ban on {}", name(user)),
AuditKind::InviteCreated { role, to, .. } => match to {
Some(u) => format!("{by} invited {} as {role}", name(u)),
None => format!("{by} made a {role} link"),
},
AuditKind::InviteRevoked { .. } => format!("{by} revoked a link"),
AuditKind::JoinRequested { user, .. } => format!("{} asked to join", name(user)),
AuditKind::JoinDenied { user } => format!("{by} turned {} away", name(user)),
AuditKind::ConsentGranted { owner, grantee, permission, .. } => format!("{} let {} {permission}", name(owner), name(grantee)),
AuditKind::ConsentRevoked { .. } => format!("{by} took back a consent"),
AuditKind::SessionOpen { open } => format!("{by} {} the session", if *open { "opened" } else { "closed" }),
AuditKind::HostHandedOver { from, left, .. } => {
format!("{by} took over as host from {}{}", name(from), if *left { "" } else { " (who could not be reached)" })
}
}
}
pub fn chat_perms() -> weirdnet_collab::ChatPerms {
use crate::perm::{CHAT_MANAGE, CHAT_READ, CHAT_WRITE};
weirdnet_collab::ChatPerms {
read: weirdnet_collab::Permission::new(CHAT_READ),
write: weirdnet_collab::Permission::new(CHAT_WRITE),
manage: weirdnet_collab::Permission::new(CHAT_MANAGE),
}
}
pub fn mentions_in(text: &str, people: &[UserId]) -> Vec<UserId> {
let mut out: Vec<UserId> = vec![];
for w in text.split('@').skip(1) {
let tok: String = w.chars().take_while(|c| c.is_ascii_alphanumeric()).collect();
if tok.len() < 4 {
continue;
}
let hits: Vec<&UserId> = people.iter().filter(|u| u.as_str().starts_with(&tok) || u.as_str().ends_with(&tok)).collect();
if let [u] = hits.as_slice()
&& !out.contains(u)
{
out.push((*u).clone());
}
}
out
}
pub fn sign_grant(owner: &Keypair, req: &ConsentRequest, how: Duration, all_streams: bool, now: i64) -> Result<ConsentGrant, SignError> {
let mut b = [0u8; 16];
getrandom::fill(&mut b).expect("the OS random source failed");
let id: String = std::iter::once('g').chain(b.iter().flat_map(|x| format!("{x:02x}").chars().collect::<Vec<_>>())).collect();
let streams = match (&req.stream, all_streams) {
(Some(s), false) => GrantStreams::Only(vec![s.clone()]),
_ => GrantStreams::All,
};
ConsentGrant::sign(owner, &id, &req.requester, &req.project, req.permission.as_str(), streams, how, now)
}
pub fn sign_revocation(owner: &Keypair, grant: &ConsentGrant, now: i64) -> Result<Revocation, SignError> {
Revocation::sign(owner, &grant.id, now)
}
pub fn decision_word(d: &Decision, name: impl Fn(&UserId) -> String) -> String {
match d {
Decision::Allowed => "allowed".into(),
Decision::Denied => "denied".into(),
Decision::NeedsConsent { owner } => format!("needs {}'s consent", name(owner)),
}
}
pub fn why_lines(e: &Explained, name: impl Fn(&UserId) -> String) -> Vec<String> {
let eff = |x: &Effect| if matches!(x, Effect::Allow) { "allows" } else { "denies" };
e.chain
.iter()
.map(|s| match s {
Step::Banned => "banned from the project".into(),
Step::NotMember => "not a member".into(),
Step::SessionClosed => "the session is closed".into(),
Step::MemberRule { rule, effect, set_by, .. } => {
format!("a rule for this person {} it (rule {rule}, set by {})", eff(effect), name(set_by))
}
Step::RoleRule { role, rule, effect, set_by, .. } => {
format!("a rule for every {role} {} it (rule {rule}, set by {})", eff(effect), name(set_by))
}
Step::ExpiredRule { rule } => format!("rule {rule} has expired and was ignored"),
Step::RoleDefault { role, granted } => format!("the {role} role {} it by default", if *granted { "has" } else { "does not have" }),
Step::OwnAudio => "it is your own audio".into(),
Step::Consent { owner, duration, .. } => {
format!("{} said yes{}", name(owner), if matches!(duration, Duration::Once) { " once" } else { ", always" })
}
Step::ConsentMissing { owner } => format!("{} has not said yes", name(owner)),
Step::NoOwnerNamed => "no audio owner was named".into(),
Step::LocalGate { name: g } => format!("turned on locally ({g})"),
Step::DefaultDeny => "nothing allows it".into(),
})
.collect()
}
pub fn streams_word(g: &ConsentGrant) -> String {
match &g.streams {
GrantStreams::All => "all streams".into(),
GrantStreams::Only(v) => v.iter().map(StreamId::to_string).collect::<Vec<_>>().join(", "),
}
}
pub mod client {
use super::*;
use weirdnet_service::{ServiceError, Session};
fn bad(what: &str) -> ServiceError {
ServiceError::App { code: "bad-response".into(), message: format!("not {what}") }
}
pub async fn open(client: &weirdnet_service::Client, host: &UserId) -> Result<Session<Req, Resp>, ServiceError> {
client.session::<Req, Resp>(host.as_str(), &protocol()).await
}
pub async fn join(s: &Session<Req, Resp>, link: &str) -> Result<Answer, ServiceError> {
match s.call(&Req::Join { link: link.into() }).await? {
Resp::Answer(a) => Ok(a),
_ => Err(bad("an answer")),
}
}
pub async fn status(s: &Session<Req, Resp>, project: &ProjectId) -> Result<Answer, ServiceError> {
match s.call(&Req::Status { project: project.clone() }).await? {
Resp::Answer(a) => Ok(a),
_ => Err(bad("an answer")),
}
}
pub async fn sync(s: &Session<Req, Resp>, project: &ProjectId) -> Result<ProjectView, ServiceError> {
match s.call(&Req::Sync { project: project.clone() }).await? {
Resp::View(v) => Ok(*v),
_ => Err(bad("a view")),
}
}
pub async fn here(s: &Session<Req, Resp>, project: &ProjectId, app: &str, activity: Activity) -> Result<(), ServiceError> {
here_as(s, project, app, activity, None).await
}
pub async fn here_as(s: &Session<Req, Resp>, project: &ProjectId, app: &str, activity: Activity, peer: Option<&str>) -> Result<(), ServiceError> {
match s.call(&Req::Here { project: project.clone(), app: app.into(), activity, peer: peer.map(str::to_string) }).await? {
Resp::Noted => Ok(()),
_ => Err(bad("noted")),
}
}
pub async fn peers(s: &Session<Req, Resp>, project: &ProjectId, permission: &str) -> Result<Vec<PeerRight>, ServiceError> {
match s.call(&Req::Peers { project: project.clone(), permission: permission.into() }).await? {
Resp::Peers(p) => Ok(p),
_ => Err(bad("peers")),
}
}
pub async fn can(
s: &Session<Req, Resp>,
project: &ProjectId,
permission: &str,
owner: Option<&UserId>,
stream: Option<&str>,
act: bool,
) -> Result<Explained, ServiceError> {
let req =
Req::Can { project: project.clone(), permission: permission.into(), owner: owner.cloned(), stream: stream.map(str::to_string), act };
match s.call(&req).await? {
Resp::Decision(e) => Ok(*e),
_ => Err(bad("a decision")),
}
}
pub async fn grant(s: &Session<Req, Resp>, grant: ConsentGrant, entry: Option<AuditEntry>) -> Result<(), ServiceError> {
match s.call(&Req::Grant { grant, entry }).await? {
Resp::Noted => Ok(()),
_ => Err(bad("noted")),
}
}
pub async fn revoke(s: &Session<Req, Resp>, revocation: Revocation, entry: Option<AuditEntry>) -> Result<(), ServiceError> {
match s.call(&Req::Revoke { revocation, entry }).await? {
Resp::Noted => Ok(()),
_ => Err(bad("noted")),
}
}
pub async fn decline(s: &Session<Req, Resp>, request: ConsentRequest) -> Result<(), ServiceError> {
match s.call(&Req::Decline { request }).await? {
Resp::Noted => Ok(()),
_ => Err(bad("noted")),
}
}
pub async fn say(
s: &Session<Req, Resp>,
me: &Keypair,
project: &ProjectId,
text: &str,
mentions: Vec<UserId>,
now: i64,
) -> Result<ChatMessage, ServiceError> {
let message = ChatMessage::sign(me, project, text, mentions, now).map_err(|e| bad(&e.to_string()))?;
match s.call(&Req::Say { message: message.clone() }).await? {
Resp::Seq(_) => Ok(message),
_ => Err(bad("a sequence number")),
}
}
pub async fn react(s: &Session<Req, Resp>, project: &ProjectId, message: &RecordId, reaction: &str, on: bool) -> Result<u64, ServiceError> {
match s.call(&Req::React { project: project.clone(), message: message.clone(), reaction: reaction.into(), on }).await? {
Resp::Seq(n) => Ok(n),
_ => Err(bad("a sequence number")),
}
}
pub async fn unsay(s: &Session<Req, Resp>, project: &ProjectId, message: &RecordId) -> Result<u64, ServiceError> {
match s.call(&Req::Unsay { project: project.clone(), message: message.clone() }).await? {
Resp::Seq(n) => Ok(n),
_ => Err(bad("a sequence number")),
}
}
pub async fn chat(s: &Session<Req, Resp>, project: &ProjectId, since: u64) -> Result<ChatPage, ServiceError> {
match s.call(&Req::Chat { project: project.clone(), since }).await? {
Resp::Chat(p) => Ok(p),
_ => Err(bad("chat")),
}
}
pub async fn cert(s: &Session<Req, Resp>, project: &ProjectId) -> Result<crate::stage::Cert, ServiceError> {
match s.call(&Req::Cert { project: project.clone() }).await? {
Resp::Cert(c) => Ok(*c),
_ => Err(bad("a certificate")),
}
}
}