Skip to main content

weirdnet_songnotes/
link.rs

1//! The two SongNotes links: join a session, and open a panel of a project.
2//!
3//! * `weirdnet-songnotes://join/<token>`: the token names the project and the invite, and may
4//!   name the host and addresses to dial.
5//! * `weirdnet-songnotes://collab/<project>/<panel>`: open a project's panel (the panel is optional).
6use std::fmt;
7use std::str::FromStr;
8use weirdnet_collab::{ProjectId, RecordId};
9use weirdnet_contacts::UserId;
10
11const SCHEME: &str = "weirdnet-songnotes://";
12
13/// Why a link did not parse.
14#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
15pub enum LinkError {
16    /// Not a `weirdnet-songnotes://` link.
17    #[error("not a weirdnet-songnotes link")]
18    Scheme,
19    /// The link is not one of the known forms.
20    #[error("unknown link form")]
21    Form,
22    /// A part is empty or has a bad percent escape.
23    #[error("malformed link")]
24    Malformed,
25}
26
27fn unreserved(b: u8) -> bool {
28    b.is_ascii_alphanumeric() || b == b'-' || b == b'_'
29}
30
31fn encode(s: &str) -> String {
32    let mut out = String::new();
33    for b in s.bytes() {
34        if unreserved(b) {
35            out.push(b as char);
36        } else {
37            out.push_str(&format!("%{b:02X}"));
38        }
39    }
40    out
41}
42
43fn decode(s: &str) -> Result<String, LinkError> {
44    let b = s.as_bytes();
45    let mut out = Vec::new();
46    let mut i = 0;
47    while i < b.len() {
48        if b[i] == b'%' {
49            let hex = s.get(i + 1..i + 3).ok_or(LinkError::Malformed)?;
50            out.push(u8::from_str_radix(hex, 16).map_err(|_| LinkError::Malformed)?);
51            i += 3;
52        } else {
53            out.push(b[i]);
54            i += 1;
55        }
56    }
57    String::from_utf8(out).map_err(|_| LinkError::Malformed)
58}
59
60fn rest(s: &str) -> Result<&str, LinkError> {
61    s.strip_prefix(SCHEME).ok_or(LinkError::Scheme)
62}
63
64/// A link that joins a session. It names the project and the invite, and may name the host
65/// to ask and addresses to try first; without a host the app has to know who hosts the project.
66#[derive(Clone, Debug, PartialEq, Eq)]
67#[non_exhaustive]
68pub struct JoinLink {
69    /// The project.
70    pub project: ProjectId,
71    /// The invite to redeem.
72    pub invite: RecordId,
73    /// The host to ask, if the link names one.
74    pub host: Option<UserId>,
75    /// Addresses (multiaddrs) to try first when dialling the host. They reveal where the host
76    /// can be reached, so an app adds them only when the user shares the link directly.
77    pub addrs: Vec<String>,
78}
79
80impl JoinLink {
81    /// A link for `invite` of `project`, with no host and no addresses.
82    pub fn new(project: ProjectId, invite: RecordId) -> Self {
83        JoinLink { project, invite, host: None, addrs: Vec::new() }
84    }
85
86    /// The same link naming `host`.
87    pub fn with_host(mut self, host: UserId) -> Self {
88        self.host = Some(host);
89        self
90    }
91
92    /// The same link with dial hints.
93    pub fn with_addrs(mut self, addrs: impl IntoIterator<Item = String>) -> Self {
94        self.addrs = addrs.into_iter().collect();
95        self
96    }
97
98    /// The opaque token in the link: the encoded project and invite, then the host and the
99    /// addresses if present, separated by dots (addresses by `~`).
100    pub fn token(&self) -> String {
101        let mut t = format!("{}.{}", encode(self.project.as_str()), encode(self.invite.as_str()));
102        if self.host.is_some() || !self.addrs.is_empty() {
103            t.push('.');
104            if let Some(h) = &self.host {
105                t.push_str(&encode(h.as_str()));
106            }
107        }
108        if !self.addrs.is_empty() {
109            t.push('.');
110            t.push_str(&self.addrs.iter().map(|a| encode(a)).collect::<Vec<_>>().join("~"));
111        }
112        t
113    }
114
115    /// Parse a bare token. Two-part tokens from 0.1 links still parse.
116    pub fn from_token(token: &str) -> Result<Self, LinkError> {
117        let parts: Vec<&str> = token.split('.').collect();
118        if !(2..=4).contains(&parts.len()) || parts[0].is_empty() || parts[1].is_empty() {
119            return Err(LinkError::Malformed);
120        }
121        let mut l = JoinLink::new(ProjectId::new(decode(parts[0])?), RecordId::new(decode(parts[1])?));
122        if let Some(h) = parts.get(2).filter(|h| !h.is_empty()) {
123            l.host = Some(UserId::parse(&decode(h)?).map_err(|_| LinkError::Malformed)?);
124        } else if parts.len() == 3 {
125            return Err(LinkError::Malformed);
126        }
127        if let Some(a) = parts.get(3) {
128            l.addrs = a.split('~').map(decode).collect::<Result<Vec<_>, _>>()?;
129            if l.addrs.iter().any(|a| a.is_empty()) {
130                return Err(LinkError::Malformed);
131            }
132        }
133        Ok(l)
134    }
135}
136
137impl fmt::Display for JoinLink {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        write!(f, "{SCHEME}join/{}", self.token())
140    }
141}
142
143impl FromStr for JoinLink {
144    type Err = LinkError;
145    fn from_str(s: &str) -> Result<Self, LinkError> {
146        let r = rest(s.trim())?;
147        let token = r.strip_prefix("join/").ok_or(LinkError::Form)?;
148        JoinLink::from_token(token)
149    }
150}
151
152/// A part of the collab window.
153#[derive(Clone, Debug, PartialEq, Eq)]
154pub enum Panel {
155    /// The collab home: the session at a glance.
156    Collab,
157    /// People, roles and presence.
158    People,
159    /// Chat and the activity feed.
160    Chat,
161    /// The stage: audio streams and talkback.
162    Stage,
163    /// Routing.
164    Routing,
165    /// Recordings.
166    Recordings,
167    /// Session settings, permissions and the audit log.
168    Settings,
169    /// A panel this version does not know; kept so a newer link survives a round trip.
170    Other(String),
171}
172
173impl Panel {
174    /// The panel's name in a link.
175    pub fn name(&self) -> &str {
176        match self {
177            Panel::Collab => "collab",
178            Panel::People => "people",
179            Panel::Chat => "chat",
180            Panel::Stage => "stage",
181            Panel::Routing => "routing",
182            Panel::Recordings => "recordings",
183            Panel::Settings => "settings",
184            Panel::Other(s) => s,
185        }
186    }
187
188    fn parse(s: &str) -> Panel {
189        match s {
190            "collab" => Panel::Collab,
191            "people" => Panel::People,
192            "chat" => Panel::Chat,
193            "stage" => Panel::Stage,
194            "routing" => Panel::Routing,
195            "recordings" => Panel::Recordings,
196            "settings" => Panel::Settings,
197            other => Panel::Other(other.to_string()),
198        }
199    }
200}
201
202/// A link that opens a project's panel.
203#[derive(Clone, Debug, PartialEq, Eq)]
204pub struct DeepLink {
205    /// The project.
206    pub project: ProjectId,
207    /// The panel.
208    pub panel: Panel,
209}
210
211impl fmt::Display for DeepLink {
212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213        write!(f, "{SCHEME}collab/{}/{}", encode(self.project.as_str()), encode(self.panel.name()))
214    }
215}
216
217impl FromStr for DeepLink {
218    type Err = LinkError;
219    fn from_str(s: &str) -> Result<Self, LinkError> {
220        let r = rest(s.trim())?;
221        let r = r.strip_prefix("collab/").ok_or(LinkError::Form)?;
222        let (p, panel) = match r.split_once('/') {
223            Some((p, panel)) => (p, panel.trim_end_matches('/')),
224            None => (r, "collab"),
225        };
226        if p.is_empty() || panel.is_empty() || panel.contains('/') {
227            return Err(LinkError::Malformed);
228        }
229        Ok(DeepLink { project: ProjectId::new(&decode(p)?), panel: Panel::parse(&decode(panel)?) })
230    }
231}
232
233/// Either kind of link, for an app's single "open this" entry point.
234#[derive(Clone, Debug, PartialEq, Eq)]
235pub enum AnyLink {
236    /// Join a session.
237    Join(JoinLink),
238    /// Open a panel.
239    Open(DeepLink),
240}
241
242impl FromStr for AnyLink {
243    type Err = LinkError;
244    fn from_str(s: &str) -> Result<Self, LinkError> {
245        let r = rest(s.trim())?;
246        if r.starts_with("join/") {
247            Ok(AnyLink::Join(s.parse()?))
248        } else if r.starts_with("collab/") {
249            Ok(AnyLink::Open(s.parse()?))
250        } else {
251            Err(LinkError::Form)
252        }
253    }
254}