use std::fmt;
use std::str::FromStr;
use weirdnet_collab::{ProjectId, RecordId};
use weirdnet_contacts::UserId;
const SCHEME: &str = "weirdnet-songnotes://";
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum LinkError {
#[error("not a weirdnet-songnotes link")]
Scheme,
#[error("unknown link form")]
Form,
#[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)
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct JoinLink {
pub project: ProjectId,
pub invite: RecordId,
pub host: Option<UserId>,
pub addrs: Vec<String>,
}
impl JoinLink {
pub fn new(project: ProjectId, invite: RecordId) -> Self {
JoinLink { project, invite, host: None, addrs: Vec::new() }
}
pub fn with_host(mut self, host: UserId) -> Self {
self.host = Some(host);
self
}
pub fn with_addrs(mut self, addrs: impl IntoIterator<Item = String>) -> Self {
self.addrs = addrs.into_iter().collect();
self
}
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
}
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)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Panel {
Collab,
People,
Chat,
Stage,
Routing,
Recordings,
Settings,
Other(String),
}
impl Panel {
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()),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DeepLink {
pub project: ProjectId,
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)?) })
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AnyLink {
Join(JoinLink),
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)
}
}
}