weirdnet_songnotes/
link.rs1use std::fmt;
7use std::str::FromStr;
8use weirdnet_collab::{ProjectId, RecordId};
9use weirdnet_contacts::UserId;
10
11const SCHEME: &str = "weirdnet-songnotes://";
12
13#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
15pub enum LinkError {
16 #[error("not a weirdnet-songnotes link")]
18 Scheme,
19 #[error("unknown link form")]
21 Form,
22 #[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#[derive(Clone, Debug, PartialEq, Eq)]
67#[non_exhaustive]
68pub struct JoinLink {
69 pub project: ProjectId,
71 pub invite: RecordId,
73 pub host: Option<UserId>,
75 pub addrs: Vec<String>,
78}
79
80impl JoinLink {
81 pub fn new(project: ProjectId, invite: RecordId) -> Self {
83 JoinLink { project, invite, host: None, addrs: Vec::new() }
84 }
85
86 pub fn with_host(mut self, host: UserId) -> Self {
88 self.host = Some(host);
89 self
90 }
91
92 pub fn with_addrs(mut self, addrs: impl IntoIterator<Item = String>) -> Self {
94 self.addrs = addrs.into_iter().collect();
95 self
96 }
97
98 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 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#[derive(Clone, Debug, PartialEq, Eq)]
154pub enum Panel {
155 Collab,
157 People,
159 Chat,
161 Stage,
163 Routing,
165 Recordings,
167 Settings,
169 Other(String),
171}
172
173impl Panel {
174 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#[derive(Clone, Debug, PartialEq, Eq)]
204pub struct DeepLink {
205 pub project: ProjectId,
207 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#[derive(Clone, Debug, PartialEq, Eq)]
235pub enum AnyLink {
236 Join(JoinLink),
238 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}