use std::fmt;
use std::str::FromStr;
use weirdnet_collab::{ProjectId, RecordId};
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)]
pub struct JoinLink {
pub project: ProjectId,
pub invite: RecordId,
}
impl JoinLink {
pub fn new(project: ProjectId, invite: RecordId) -> Self {
JoinLink { project, invite }
}
pub fn token(&self) -> String {
format!("{}.{}", encode(self.project.as_str()), encode(self.invite.as_str()))
}
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)
}
}
#[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)
}
}
}