weirdnet-songnotes 0.1.2

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.
//! * `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};

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.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JoinLink {
    /// The project.
    pub project: ProjectId,
    /// The invite to redeem.
    pub invite: RecordId,
}

impl JoinLink {
    /// A link for `invite` of `project`.
    pub fn new(project: ProjectId, invite: RecordId) -> Self {
        JoinLink { project, invite }
    }

    /// The opaque token in the link: the encoded project, a dot, the encoded invite.
    pub fn token(&self) -> String {
        format!("{}.{}", encode(self.project.as_str()), encode(self.invite.as_str()))
    }

    /// Parse a bare token.
    pub fn from_token(token: &str) -> Result<Self, LinkError> {
        let (p, i) = token.split_once('.').ok_or(LinkError::Malformed)?;
        if p.is_empty() || i.is_empty() || i.contains('.') {
            return Err(LinkError::Malformed);
        }
        Ok(JoinLink { project: ProjectId::new(&decode(p)?), invite: RecordId::new(&decode(i)?) })
    }
}

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)
        }
    }
}