1use crate::session::ConsentRequest;
10use serde::{Deserialize, Serialize};
11use weirdnet_collab::{
12 AuditEntry, AuditKind, ChatItem, ChatMessage, ConsentGrant, Decision, Duration, Effect, Explained, GrantStreams, ProjectId, RecordId, Revocation,
13 RoleId, SignError, Step, StreamId,
14};
15use weirdnet_contacts::UserId;
16use weirdnet_net::Keypair;
17use weirdnet_service::ProtocolId;
18
19pub const PROTOCOL: &str = "/songnotes/collab";
21pub const VERSION: u32 = 1;
23pub const RE_AUTH_MS: i64 = 5_000;
25pub const PRESENCE_REFRESH_MS: i64 = 20_000;
27pub const PRESENCE_TTL_MS: i64 = 60_000;
29const _: () = assert!(RE_AUTH_MS < PRESENCE_REFRESH_MS && PRESENCE_REFRESH_MS < PRESENCE_TTL_MS);
30
31pub fn protocol() -> ProtocolId {
33 ProtocolId::new(PROTOCOL, VERSION).expect("a valid protocol id")
34}
35
36#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
38pub enum Standing {
39 Member(RoleId),
41 Pending,
43 Out,
45 Banned,
47}
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
51pub enum Activity {
52 Active,
54 Idle,
56}
57
58#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
60pub struct Here {
61 pub app: String,
63 pub activity: Activity,
65 pub at_ms: i64,
67 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub peer: Option<String>,
71}
72
73pub const PEER_PERMISSIONS: &[&str] = &[crate::perm::ROUTE_CONNECT];
75
76#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
78pub struct PeerRight {
79 pub peer: String,
81 pub user: UserId,
83 pub app: String,
85 pub right: Explained,
87}
88
89#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
91pub struct Person {
92 pub user: UserId,
94 pub role: RoleId,
96 pub apps: Vec<Here>,
98}
99
100#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
102pub struct ProjectView {
103 pub project: ProjectId,
105 pub title: String,
107 pub host: UserId,
109 pub standing: Standing,
111 pub people: Vec<Person>,
113 pub audit: Vec<AuditEntry>,
115 #[serde(default)]
117 pub consent_requests: Vec<ConsentRequest>,
118 #[serde(default)]
120 pub grants: Vec<ConsentGrant>,
121 #[serde(default)]
123 pub rights: Vec<Explained>,
124 pub at_ms: i64,
126}
127
128impl ProjectView {
129 pub fn person(&self, user: &UserId) -> Option<&Person> {
131 self.people.iter().find(|p| &p.user == user)
132 }
133
134 pub fn right(&self, permission: &str) -> Option<&Explained> {
136 self.rights.iter().find(|e| e.permission.as_str() == permission)
137 }
138
139 pub fn audit_verifies(&self) -> bool {
141 self.audit.iter().all(AuditEntry::verify)
142 }
143}
144
145#[derive(Clone, Debug, Serialize, Deserialize)]
147pub enum Req {
148 Join {
150 link: String,
152 },
153 Status {
155 project: ProjectId,
157 },
158 Sync {
160 project: ProjectId,
162 },
163 Here {
165 project: ProjectId,
167 app: String,
169 activity: Activity,
171 #[serde(default, skip_serializing_if = "Option::is_none")]
173 peer: Option<String>,
174 },
175 Peers {
178 project: ProjectId,
180 permission: String,
182 },
183 Can {
187 project: ProjectId,
189 permission: String,
191 owner: Option<UserId>,
193 stream: Option<String>,
195 act: bool,
197 },
198 Grant {
200 grant: ConsentGrant,
202 #[serde(default)]
205 entry: Option<AuditEntry>,
206 },
207 Revoke {
209 revocation: Revocation,
211 #[serde(default)]
213 entry: Option<AuditEntry>,
214 },
215 Decline {
217 request: ConsentRequest,
219 },
220 Say {
222 message: ChatMessage,
224 },
225 React {
227 project: ProjectId,
229 message: RecordId,
231 reaction: String,
233 on: bool,
235 },
236 Unsay {
238 project: ProjectId,
240 message: RecordId,
242 },
243 Chat {
246 project: ProjectId,
248 since: u64,
250 },
251 Cert {
254 project: ProjectId,
256 },
257 Talk {
259 project: ProjectId,
261 },
262 Mic {
265 project: ProjectId,
267 peer: String,
269 addrs: Vec<String>,
271 stream: String,
273 live: bool,
275 },
276 MuteMic {
278 project: ProjectId,
280 user: Option<UserId>,
282 muted: bool,
284 },
285}
286
287#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
289pub struct Answer {
290 pub project: ProjectId,
292 pub title: Option<String>,
294 pub standing: Standing,
296}
297
298#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
300pub struct ChatPage {
301 pub items: Vec<ChatItem>,
303 pub seq: u64,
305}
306
307#[derive(Clone, Debug, Serialize, Deserialize)]
309pub enum Resp {
310 Answer(Answer),
312 View(Box<ProjectView>),
314 Noted,
316 Decision(Box<Explained>),
318 Seq(u64),
320 Chat(ChatPage),
322 Cert(Box<crate::stage::Cert>),
324 Talk(Box<crate::talk::TalkState>),
326 Peers(Vec<PeerRight>),
328}
329
330pub fn audit_line(e: &AuditEntry, name: impl Fn(&UserId) -> String) -> String {
332 let by = name(&e.by);
333 match &e.kind {
334 AuditKind::RuleSet { permission, effect, member, role, .. } => {
335 let who = member.as_ref().map(&name).or_else(|| role.as_ref().map(|r| format!("every {r}"))).unwrap_or_else(|| "everyone".into());
336 let verb = if matches!(effect, weirdnet_collab::Effect::Allow) { "allowed" } else { "denied" };
337 format!("{by} {verb} {permission} for {who}")
338 }
339 AuditKind::RuleRemoved { .. } => format!("{by} removed a rule"),
340 AuditKind::RoleChanged { user, from, to } => format!("{by} changed {} from {from} to {to}", name(user)),
341 AuditKind::MemberJoined { user, role, .. } => format!("{} joined as {role}", name(user)),
342 AuditKind::MemberKicked { user } => format!("{by} removed {}", name(user)),
343 AuditKind::MemberBanned { user } => format!("{by} banned {}", name(user)),
344 AuditKind::MemberUnbanned { user } => format!("{by} lifted the ban on {}", name(user)),
345 AuditKind::InviteCreated { role, to, .. } => match to {
346 Some(u) => format!("{by} invited {} as {role}", name(u)),
347 None => format!("{by} made a {role} link"),
348 },
349 AuditKind::InviteRevoked { .. } => format!("{by} revoked a link"),
350 AuditKind::JoinRequested { user, .. } => format!("{} asked to join", name(user)),
351 AuditKind::JoinDenied { user } => format!("{by} turned {} away", name(user)),
352 AuditKind::ConsentGranted { owner, grantee, permission, .. } => format!("{} let {} {permission}", name(owner), name(grantee)),
353 AuditKind::ConsentRevoked { .. } => format!("{by} took back a consent"),
354 AuditKind::SessionOpen { open } => format!("{by} {} the session", if *open { "opened" } else { "closed" }),
355 AuditKind::HostHandedOver { from, left, .. } => {
356 format!("{by} took over as host from {}{}", name(from), if *left { "" } else { " (who could not be reached)" })
357 }
358 }
359}
360
361pub fn chat_perms() -> weirdnet_collab::ChatPerms {
363 use crate::perm::{CHAT_MANAGE, CHAT_READ, CHAT_WRITE};
364 weirdnet_collab::ChatPerms {
365 read: weirdnet_collab::Permission::new(CHAT_READ),
366 write: weirdnet_collab::Permission::new(CHAT_WRITE),
367 manage: weirdnet_collab::Permission::new(CHAT_MANAGE),
368 }
369}
370
371pub fn mentions_in(text: &str, people: &[UserId]) -> Vec<UserId> {
374 let mut out: Vec<UserId> = vec![];
375 for w in text.split('@').skip(1) {
376 let tok: String = w.chars().take_while(|c| c.is_ascii_alphanumeric()).collect();
377 if tok.len() < 4 {
378 continue;
379 }
380 let hits: Vec<&UserId> = people.iter().filter(|u| u.as_str().starts_with(&tok) || u.as_str().ends_with(&tok)).collect();
381 if let [u] = hits.as_slice()
382 && !out.contains(u)
383 {
384 out.push((*u).clone());
385 }
386 }
387 out
388}
389
390pub fn sign_grant(owner: &Keypair, req: &ConsentRequest, how: Duration, all_streams: bool, now: i64) -> Result<ConsentGrant, SignError> {
394 let mut b = [0u8; 16];
395 getrandom::fill(&mut b).expect("the OS random source failed");
396 let id: String = std::iter::once('g').chain(b.iter().flat_map(|x| format!("{x:02x}").chars().collect::<Vec<_>>())).collect();
397 let streams = match (&req.stream, all_streams) {
398 (Some(s), false) => GrantStreams::Only(vec![s.clone()]),
399 _ => GrantStreams::All,
400 };
401 ConsentGrant::sign(owner, &id, &req.requester, &req.project, req.permission.as_str(), streams, how, now)
402}
403
404pub fn sign_revocation(owner: &Keypair, grant: &ConsentGrant, now: i64) -> Result<Revocation, SignError> {
406 Revocation::sign(owner, &grant.id, now)
407}
408
409pub fn decision_word(d: &Decision, name: impl Fn(&UserId) -> String) -> String {
411 match d {
412 Decision::Allowed => "allowed".into(),
413 Decision::Denied => "denied".into(),
414 Decision::NeedsConsent { owner } => format!("needs {}'s consent", name(owner)),
415 }
416}
417
418pub fn why_lines(e: &Explained, name: impl Fn(&UserId) -> String) -> Vec<String> {
421 let eff = |x: &Effect| if matches!(x, Effect::Allow) { "allows" } else { "denies" };
422 e.chain
423 .iter()
424 .map(|s| match s {
425 Step::Banned => "banned from the project".into(),
426 Step::NotMember => "not a member".into(),
427 Step::SessionClosed => "the session is closed".into(),
428 Step::MemberRule { rule, effect, set_by, .. } => {
429 format!("a rule for this person {} it (rule {rule}, set by {})", eff(effect), name(set_by))
430 }
431 Step::RoleRule { role, rule, effect, set_by, .. } => {
432 format!("a rule for every {role} {} it (rule {rule}, set by {})", eff(effect), name(set_by))
433 }
434 Step::ExpiredRule { rule } => format!("rule {rule} has expired and was ignored"),
435 Step::RoleDefault { role, granted } => format!("the {role} role {} it by default", if *granted { "has" } else { "does not have" }),
436 Step::OwnAudio => "it is your own audio".into(),
437 Step::Consent { owner, duration, .. } => {
438 format!("{} said yes{}", name(owner), if matches!(duration, Duration::Once) { " once" } else { ", always" })
439 }
440 Step::ConsentMissing { owner } => format!("{} has not said yes", name(owner)),
441 Step::NoOwnerNamed => "no audio owner was named".into(),
442 Step::LocalGate { name: g } => format!("turned on locally ({g})"),
443 Step::DefaultDeny => "nothing allows it".into(),
444 })
445 .collect()
446}
447
448pub fn streams_word(g: &ConsentGrant) -> String {
450 match &g.streams {
451 GrantStreams::All => "all streams".into(),
452 GrantStreams::Only(v) => v.iter().map(StreamId::to_string).collect::<Vec<_>>().join(", "),
453 }
454}
455
456pub mod client {
459 use super::*;
460 use weirdnet_service::{ServiceError, Session};
461
462 fn bad(what: &str) -> ServiceError {
463 ServiceError::App { code: "bad-response".into(), message: format!("not {what}") }
464 }
465
466 pub async fn open(client: &weirdnet_service::Client, host: &UserId) -> Result<Session<Req, Resp>, ServiceError> {
468 client.session::<Req, Resp>(host.as_str(), &protocol()).await
469 }
470
471 pub async fn join(s: &Session<Req, Resp>, link: &str) -> Result<Answer, ServiceError> {
473 match s.call(&Req::Join { link: link.into() }).await? {
474 Resp::Answer(a) => Ok(a),
475 _ => Err(bad("an answer")),
476 }
477 }
478
479 pub async fn status(s: &Session<Req, Resp>, project: &ProjectId) -> Result<Answer, ServiceError> {
481 match s.call(&Req::Status { project: project.clone() }).await? {
482 Resp::Answer(a) => Ok(a),
483 _ => Err(bad("an answer")),
484 }
485 }
486
487 pub async fn sync(s: &Session<Req, Resp>, project: &ProjectId) -> Result<ProjectView, ServiceError> {
489 match s.call(&Req::Sync { project: project.clone() }).await? {
490 Resp::View(v) => Ok(*v),
491 _ => Err(bad("a view")),
492 }
493 }
494
495 pub async fn here(s: &Session<Req, Resp>, project: &ProjectId, app: &str, activity: Activity) -> Result<(), ServiceError> {
497 here_as(s, project, app, activity, None).await
498 }
499
500 pub async fn here_as(s: &Session<Req, Resp>, project: &ProjectId, app: &str, activity: Activity, peer: Option<&str>) -> Result<(), ServiceError> {
502 match s.call(&Req::Here { project: project.clone(), app: app.into(), activity, peer: peer.map(str::to_string) }).await? {
503 Resp::Noted => Ok(()),
504 _ => Err(bad("noted")),
505 }
506 }
507
508 pub async fn peers(s: &Session<Req, Resp>, project: &ProjectId, permission: &str) -> Result<Vec<PeerRight>, ServiceError> {
510 match s.call(&Req::Peers { project: project.clone(), permission: permission.into() }).await? {
511 Resp::Peers(p) => Ok(p),
512 _ => Err(bad("peers")),
513 }
514 }
515 pub async fn can(
518 s: &Session<Req, Resp>,
519 project: &ProjectId,
520 permission: &str,
521 owner: Option<&UserId>,
522 stream: Option<&str>,
523 act: bool,
524 ) -> Result<Explained, ServiceError> {
525 let req =
526 Req::Can { project: project.clone(), permission: permission.into(), owner: owner.cloned(), stream: stream.map(str::to_string), act };
527 match s.call(&req).await? {
528 Resp::Decision(e) => Ok(*e),
529 _ => Err(bad("a decision")),
530 }
531 }
532
533 pub async fn grant(s: &Session<Req, Resp>, grant: ConsentGrant, entry: Option<AuditEntry>) -> Result<(), ServiceError> {
535 match s.call(&Req::Grant { grant, entry }).await? {
536 Resp::Noted => Ok(()),
537 _ => Err(bad("noted")),
538 }
539 }
540
541 pub async fn revoke(s: &Session<Req, Resp>, revocation: Revocation, entry: Option<AuditEntry>) -> Result<(), ServiceError> {
543 match s.call(&Req::Revoke { revocation, entry }).await? {
544 Resp::Noted => Ok(()),
545 _ => Err(bad("noted")),
546 }
547 }
548
549 pub async fn decline(s: &Session<Req, Resp>, request: ConsentRequest) -> Result<(), ServiceError> {
551 match s.call(&Req::Decline { request }).await? {
552 Resp::Noted => Ok(()),
553 _ => Err(bad("noted")),
554 }
555 }
556 pub async fn say(
559 s: &Session<Req, Resp>,
560 me: &Keypair,
561 project: &ProjectId,
562 text: &str,
563 mentions: Vec<UserId>,
564 now: i64,
565 ) -> Result<ChatMessage, ServiceError> {
566 let message = ChatMessage::sign(me, project, text, mentions, now).map_err(|e| bad(&e.to_string()))?;
567 match s.call(&Req::Say { message: message.clone() }).await? {
568 Resp::Seq(_) => Ok(message),
569 _ => Err(bad("a sequence number")),
570 }
571 }
572
573 pub async fn react(s: &Session<Req, Resp>, project: &ProjectId, message: &RecordId, reaction: &str, on: bool) -> Result<u64, ServiceError> {
575 match s.call(&Req::React { project: project.clone(), message: message.clone(), reaction: reaction.into(), on }).await? {
576 Resp::Seq(n) => Ok(n),
577 _ => Err(bad("a sequence number")),
578 }
579 }
580
581 pub async fn unsay(s: &Session<Req, Resp>, project: &ProjectId, message: &RecordId) -> Result<u64, ServiceError> {
583 match s.call(&Req::Unsay { project: project.clone(), message: message.clone() }).await? {
584 Resp::Seq(n) => Ok(n),
585 _ => Err(bad("a sequence number")),
586 }
587 }
588
589 pub async fn chat(s: &Session<Req, Resp>, project: &ProjectId, since: u64) -> Result<ChatPage, ServiceError> {
591 match s.call(&Req::Chat { project: project.clone(), since }).await? {
592 Resp::Chat(p) => Ok(p),
593 _ => Err(bad("chat")),
594 }
595 }
596
597 pub async fn cert(s: &Session<Req, Resp>, project: &ProjectId) -> Result<crate::stage::Cert, ServiceError> {
599 match s.call(&Req::Cert { project: project.clone() }).await? {
600 Resp::Cert(c) => Ok(*c),
601 _ => Err(bad("a certificate")),
602 }
603 }
604}