use serde::{Deserialize, Serialize};
use weirdnet_collab::{AuditEntry, AuditKind, ProjectId, RoleId};
use weirdnet_contacts::UserId;
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,
}
#[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>,
pub at_ms: i64,
}
impl ProjectView {
pub fn person(&self, user: &UserId) -> Option<&Person> {
self.people.iter().find(|p| &p.user == user)
}
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,
},
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Answer {
pub project: ProjectId,
pub title: Option<String>,
pub standing: Standing,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Resp {
Answer(Answer),
View(Box<ProjectView>),
Noted,
}
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" }),
}
}
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> {
match s.call(&Req::Here { project: project.clone(), app: app.into(), activity }).await? {
Resp::Noted => Ok(()),
_ => Err(bad("noted")),
}
}
}