weirdnet-songnotes 0.2.0

SongNotes collaboration: the roles, permissions, links and consent requests for a SongNotes session, built on weirdnet-collab.
Documentation
//! The two SongNotes links: join a session, and open a panel of a project.
//!
//! * `weirdnet-songnotes://join/<token>`: the token names the project and the invite, and may
//!   name the host and addresses to dial.
//! * `weirdnet-songnotes://collab/<project>/<panel>`: open a project's panel (the panel is optional).
use std::fmt;
use std::str::FromStr;
use weirdnet_collab::{ProjectId, RecordId};
use weirdnet_contacts::UserId;

const SCHEME: &str = "weirdnet-songnotes://";

/// Why a link did not parse.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum LinkError {
    /// Not a `weirdnet-songnotes://` link.
    #[error("not a weirdnet-songnotes link")]
    Scheme,
    /// The link is not one of the known forms.
    #[error("unknown link form")]
    Form,
    /// A part is empty or has a bad percent escape.
    #[error("malformed link")]
    Malformed,
}

fn unreserved(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'-' || b == b'_'
}

fn encode(s: &str) -> String {
    let mut out = String::new();
    for b in s.bytes() {
        if unreserved(b) {
            out.push(b as char);
        } else {
            out.push_str(&format!("%{b:02X}"));
        }
    }
    out
}

fn decode(s: &str) -> Result<String, LinkError> {
    let b = s.as_bytes();
    let mut out = Vec::new();
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%' {
            let hex = s.get(i + 1..i + 3).ok_or(LinkError::Malformed)?;
            out.push(u8::from_str_radix(hex, 16).map_err(|_| LinkError::Malformed)?);
            i += 3;
        } else {
            out.push(b[i]);
            i += 1;
        }
    }
    String::from_utf8(out).map_err(|_| LinkError::Malformed)
}

fn rest(s: &str) -> Result<&str, LinkError> {
    s.strip_prefix(SCHEME).ok_or(LinkError::Scheme)
}

/// A link that joins a session. It names the project and the invite, and may name the host
/// to ask and addresses to try first; without a host the app has to know who hosts the project.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct JoinLink {
    /// The project.
    pub project: ProjectId,
    /// The invite to redeem.
    pub invite: RecordId,
    /// The host to ask, if the link names one.
    pub host: Option<UserId>,
    /// Addresses (multiaddrs) to try first when dialling the host. They reveal where the host
    /// can be reached, so an app adds them only when the user shares the link directly.
    pub addrs: Vec<String>,
}

impl JoinLink {
    /// A link for `invite` of `project`, with no host and no addresses.
    pub fn new(project: ProjectId, invite: RecordId) -> Self {
        JoinLink { project, invite, host: None, addrs: Vec::new() }
    }

    /// The same link naming `host`.
    pub fn with_host(mut self, host: UserId) -> Self {
        self.host = Some(host);
        self
    }

    /// The same link with dial hints.
    pub fn with_addrs(mut self, addrs: impl IntoIterator<Item = String>) -> Self {
        self.addrs = addrs.into_iter().collect();
        self
    }

    /// The opaque token in the link: the encoded project and invite, then the host and the
    /// addresses if present, separated by dots (addresses by `~`).
    pub fn token(&self) -> String {
        let mut t = format!("{}.{}", encode(self.project.as_str()), encode(self.invite.as_str()));
        if self.host.is_some() || !self.addrs.is_empty() {
            t.push('.');
            if let Some(h) = &self.host {
                t.push_str(&encode(h.as_str()));
            }
        }
        if !self.addrs.is_empty() {
            t.push('.');
            t.push_str(&self.addrs.iter().map(|a| encode(a)).collect::<Vec<_>>().join("~"));
        }
        t
    }

    /// Parse a bare token. Two-part tokens from 0.1 links still parse.
    pub fn from_token(token: &str) -> Result<Self, LinkError> {
        let parts: Vec<&str> = token.split('.').collect();
        if !(2..=4).contains(&parts.len()) || parts[0].is_empty() || parts[1].is_empty() {
            return Err(LinkError::Malformed);
        }
        let mut l = JoinLink::new(ProjectId::new(decode(parts[0])?), RecordId::new(decode(parts[1])?));
        if let Some(h) = parts.get(2).filter(|h| !h.is_empty()) {
            l.host = Some(UserId::parse(&decode(h)?).map_err(|_| LinkError::Malformed)?);
        } else if parts.len() == 3 {
            return Err(LinkError::Malformed);
        }
        if let Some(a) = parts.get(3) {
            l.addrs = a.split('~').map(decode).collect::<Result<Vec<_>, _>>()?;
            if l.addrs.iter().any(|a| a.is_empty()) {
                return Err(LinkError::Malformed);
            }
        }
        Ok(l)
    }
}

impl fmt::Display for JoinLink {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{SCHEME}join/{}", self.token())
    }
}

impl FromStr for JoinLink {
    type Err = LinkError;
    fn from_str(s: &str) -> Result<Self, LinkError> {
        let r = rest(s.trim())?;
        let token = r.strip_prefix("join/").ok_or(LinkError::Form)?;
        JoinLink::from_token(token)
    }
}

/// A part of the collab window.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Panel {
    /// The collab home: the session at a glance.
    Collab,
    /// People, roles and presence.
    People,
    /// Chat and the activity feed.
    Chat,
    /// The stage: audio streams and talkback.
    Stage,
    /// Routing.
    Routing,
    /// Recordings.
    Recordings,
    /// Session settings, permissions and the audit log.
    Settings,
    /// A panel this version does not know; kept so a newer link survives a round trip.
    Other(String),
}

impl Panel {
    /// The panel's name in a link.
    pub fn name(&self) -> &str {
        match self {
            Panel::Collab => "collab",
            Panel::People => "people",
            Panel::Chat => "chat",
            Panel::Stage => "stage",
            Panel::Routing => "routing",
            Panel::Recordings => "recordings",
            Panel::Settings => "settings",
            Panel::Other(s) => s,
        }
    }

    fn parse(s: &str) -> Panel {
        match s {
            "collab" => Panel::Collab,
            "people" => Panel::People,
            "chat" => Panel::Chat,
            "stage" => Panel::Stage,
            "routing" => Panel::Routing,
            "recordings" => Panel::Recordings,
            "settings" => Panel::Settings,
            other => Panel::Other(other.to_string()),
        }
    }
}

/// A link that opens a project's panel.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DeepLink {
    /// The project.
    pub project: ProjectId,
    /// The panel.
    pub panel: Panel,
}

impl fmt::Display for DeepLink {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{SCHEME}collab/{}/{}", encode(self.project.as_str()), encode(self.panel.name()))
    }
}

impl FromStr for DeepLink {
    type Err = LinkError;
    fn from_str(s: &str) -> Result<Self, LinkError> {
        let r = rest(s.trim())?;
        let r = r.strip_prefix("collab/").ok_or(LinkError::Form)?;
        let (p, panel) = match r.split_once('/') {
            Some((p, panel)) => (p, panel.trim_end_matches('/')),
            None => (r, "collab"),
        };
        if p.is_empty() || panel.is_empty() || panel.contains('/') {
            return Err(LinkError::Malformed);
        }
        Ok(DeepLink { project: ProjectId::new(&decode(p)?), panel: Panel::parse(&decode(panel)?) })
    }
}

/// Either kind of link, for an app's single "open this" entry point.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AnyLink {
    /// Join a session.
    Join(JoinLink),
    /// Open a panel.
    Open(DeepLink),
}

impl FromStr for AnyLink {
    type Err = LinkError;
    fn from_str(s: &str) -> Result<Self, LinkError> {
        let r = rest(s.trim())?;
        if r.starts_with("join/") {
            Ok(AnyLink::Join(s.parse()?))
        } else if r.starts_with("collab/") {
            Ok(AnyLink::Open(s.parse()?))
        } else {
            Err(LinkError::Form)
        }
    }
}