weirdnet-songnotes 0.8.0

SongNotes collaboration: the roles, permissions, links and consent requests for a SongNotes session, built on weirdnet-collab.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
//! The SongNotes collab protocol, `/songnotes/collab`: what any SongNotes app asks the host of a
//! project. The collab app serves it on the host; stage apps (drum machine, monitor, controller)
//! use [`client`] to join, read where they stand, report which app the person is in and read
//! who else is here.
//!
//! A live app re-reads its standing every [`RE_AUTH_MS`], so a role change or a kick reaches it
//! within that interval. Presence is reported every [`PRESENCE_REFRESH_MS`] and is gone
//! [`PRESENCE_TTL_MS`] after the last report.
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;

/// The protocol id.
pub const PROTOCOL: &str = "/songnotes/collab";
/// The protocol version.
pub const VERSION: u32 = 1;
/// How often a live app re-reads its standing (the re-authorisation interval).
pub const RE_AUTH_MS: i64 = 5_000;
/// How often an app reports that the person is in it.
pub const PRESENCE_REFRESH_MS: i64 = 20_000;
/// How long a report counts.
pub const PRESENCE_TTL_MS: i64 = 60_000;
const _: () = assert!(RE_AUTH_MS < PRESENCE_REFRESH_MS && PRESENCE_REFRESH_MS < PRESENCE_TTL_MS);

/// The protocol id as a [`ProtocolId`].
pub fn protocol() -> ProtocolId {
    ProtocolId::new(PROTOCOL, VERSION).expect("a valid protocol id")
}

/// Where someone stands in a project.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Standing {
    /// A member with this role.
    Member(RoleId),
    /// Waiting for the host.
    Pending,
    /// Not in: never asked, turned away, kicked, or their link was revoked.
    Out,
    /// Banned.
    Banned,
}

/// Whether the person is using the app or it is in the background.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum Activity {
    /// In front, in use.
    Active,
    /// Open but not in use.
    Idle,
}

/// "I am in this app": what an app reports for its person.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Here {
    /// The app, such as `collab` or `drummachine`.
    pub app: String,
    /// Active or idle.
    pub activity: Activity,
    /// When the report was made (the host's clock when it took it in).
    pub at_ms: i64,
}

/// One person as the project shows them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Person {
    /// Who.
    pub user: UserId,
    /// Their role.
    pub role: RoleId,
    /// The apps they are in now, newest report first (empty: offline).
    pub apps: Vec<Here>,
}

/// What a member sees of a project.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectView {
    /// The project.
    pub project: ProjectId,
    /// Its title.
    pub title: String,
    /// The host.
    pub host: UserId,
    /// Where the caller stands.
    pub standing: Standing,
    /// The members, the host first.
    pub people: Vec<Person>,
    /// The audit entries the caller is part of (all of them for the host), oldest first.
    pub audit: Vec<AuditEntry>,
    /// Consent questions waiting for the caller (as the audio's owner).
    #[serde(default)]
    pub consent_requests: Vec<ConsentRequest>,
    /// Live consent grants the caller gave or holds.
    #[serde(default)]
    pub grants: Vec<ConsentGrant>,
    /// The caller's own rights, one decision per permission in the catalog, with the reasons.
    #[serde(default)]
    pub rights: Vec<Explained>,
    /// The host's clock when the view was made.
    pub at_ms: i64,
}

impl ProjectView {
    /// One person.
    pub fn person(&self, user: &UserId) -> Option<&Person> {
        self.people.iter().find(|p| &p.user == user)
    }

    /// The caller's decision for `permission`, if the view has it.
    pub fn right(&self, permission: &str) -> Option<&Explained> {
        self.rights.iter().find(|e| e.permission.as_str() == permission)
    }

    /// Whether every audit entry's signature holds.
    pub fn audit_verifies(&self) -> bool {
        self.audit.iter().all(AuditEntry::verify)
    }
}

/// A request to the host.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Req {
    /// Redeem this link (its text).
    Join {
        /// The link.
        link: String,
    },
    /// Where do I stand?
    Status {
        /// The project.
        project: ProjectId,
    },
    /// The project as I may see it. Members only.
    Sync {
        /// The project.
        project: ProjectId,
    },
    /// I am in this app. Members only.
    Here {
        /// The project.
        project: ProjectId,
        /// The app.
        app: String,
        /// Active or idle.
        activity: Activity,
    },
    /// May I do `permission` (to `owner`'s audio, optionally one stream)? With `act`, the caller
    /// is about to do it, so a once-only consent is used up. A "needs consent" answer puts the
    /// question in the owner's queue. Members only.
    Can {
        /// The project.
        project: ProjectId,
        /// The permission.
        permission: String,
        /// Whose audio, for gated permissions.
        owner: Option<UserId>,
        /// Which stream.
        stream: Option<String>,
        /// About to do it now.
        act: bool,
    },
    /// A consent the caller (the owner) signed.
    Grant {
        /// The grant.
        grant: ConsentGrant,
        /// The audit entry the owner signed for it ([`AuditEntry::for_grant`]); with it the grant
        /// shows in the audit as the owner's act.
        #[serde(default)]
        entry: Option<AuditEntry>,
    },
    /// The caller (the owner) takes a consent back.
    Revoke {
        /// The signed revocation.
        revocation: Revocation,
        /// The audit entry the owner signed for it ([`AuditEntry::for_revocation`]).
        #[serde(default)]
        entry: Option<AuditEntry>,
    },
    /// The caller (the owner) says no to a consent question.
    Decline {
        /// The question.
        request: ConsentRequest,
    },
    /// Post to the project chat. The caller must be the message's author. Needs `chat.write`.
    Say {
        /// The signed message ([`ChatMessage::sign`]).
        message: ChatMessage,
    },
    /// Add or take back a reaction. Needs `chat.write`.
    React {
        /// The project.
        project: ProjectId,
        /// The message.
        message: RecordId,
        /// The reaction (an emoji or a short word).
        reaction: String,
        /// Add (true) or take back.
        on: bool,
    },
    /// Delete a message: your own, or anyone's with `chat.manage`.
    Unsay {
        /// The project.
        project: ProjectId,
        /// The message.
        message: RecordId,
    },
    /// What changed in the chat after sequence number `since` (0 for all history). Needs
    /// `chat.read`.
    Chat {
        /// The project.
        project: ProjectId,
        /// The last sequence number you saw.
        since: u64,
    },
    /// The host's signed certificate of where you stand (C5), for a stage app to enforce on
    /// its own while the host does not answer.
    Cert {
        /// The project.
        project: ProjectId,
    },
}

/// The host's answer to a join or status request.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Answer {
    /// The project.
    pub project: ProjectId,
    /// Its title; told only to members and people waiting.
    pub title: Option<String>,
    /// Where the caller stands.
    pub standing: Standing,
}

/// Chat changes after a sequence number.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChatPage {
    /// Changed messages, oldest change first.
    pub items: Vec<ChatItem>,
    /// The latest sequence number; pass it as `since` next time.
    pub seq: u64,
}

/// A response.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum Resp {
    /// To `Join` and `Status`.
    Answer(Answer),
    /// To `Sync`.
    View(Box<ProjectView>),
    /// To `Here`.
    Noted,
    /// To `Can`.
    Decision(Box<Explained>),
    /// To `Say`, `React` and `Unsay`: the change's sequence number.
    Seq(u64),
    /// To `Chat`.
    Chat(ChatPage),
    /// To `Cert`.
    Cert(Box<crate::stage::Cert>),
}

/// One audit entry as a line of text; `name` turns an id into how the reader knows them.
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)" })
        }
    }
}

/// The permissions that govern project chat in SongNotes.
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),
    }
}

/// The people `text` mentions: each `@word` of at least 4 letters or digits that is the start or
/// the end of exactly one id in `people`. Each person once, in the order they appear.
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
}

/// The owner answers a consent question with yes: a grant signed with `owner`, once or always,
/// for the stream the question named or (with `all_streams`, or when it named none) all of the
/// owner's streams in the project. The id is 128 bits from the OS random source.
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)
}

/// The owner takes a grant back.
pub fn sign_revocation(owner: &Keypair, grant: &ConsentGrant, now: i64) -> Result<Revocation, SignError> {
    Revocation::sign(owner, &grant.id, now)
}

/// A decision in a few words: "allowed", "denied" or "needs NAME's consent".
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)),
    }
}

/// The reasons behind a decision, one line per step, for a "Why?" panel. The step that decided
/// names its rule, who set it and when.
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()
}

/// The streams a grant covers, in words.
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(", "),
    }
}

/// Talking to a host. Each call takes a session from
/// `weirdnet_service::Client::session::<Req, Resp>(host, &protocol())`.
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}") }
    }

    /// Open a session with `host`.
    pub async fn open(client: &weirdnet_service::Client, host: &UserId) -> Result<Session<Req, Resp>, ServiceError> {
        client.session::<Req, Resp>(host.as_str(), &protocol()).await
    }

    /// Ask to join with `link` (its text).
    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")),
        }
    }

    /// Where you stand.
    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")),
        }
    }

    /// The project as you may see it. Call every [`RE_AUTH_MS`] while the app is live.
    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")),
        }
    }

    /// Report that you are in `app`. Call every [`PRESENCE_REFRESH_MS`].
    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")),
        }
    }
    /// May you do `permission` (to `owner`'s audio, one `stream`)? With `act`, you are about to,
    /// and a once-only consent is used up. Check this before acting; the answer names its reasons.
    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")),
        }
    }

    /// Hand the host a consent you signed (see [`sign_grant`]).
    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")),
        }
    }

    /// Take a consent back (see [`sign_revocation`]).
    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")),
        }
    }

    /// Say no to a consent question.
    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")),
        }
    }
    /// Post `text` to the project chat as `me`, mentioning `mentions` (see [`mentions_in`]).
    /// Returns the message as sent.
    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")),
        }
    }

    /// Add (`on`) or take back a reaction.
    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")),
        }
    }

    /// Delete a message.
    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")),
        }
    }

    /// The chat changes after `since`.
    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")),
        }
    }

    /// The host's signed certificate of where you stand.
    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")),
        }
    }
}