Cotton code
112 lines · 3.7 KB · RustRaw
//! The deep link another Cotton app opens to place a call, and the route//! the core answers for "call this person" (Messages and People offer it).//!//! ```text//! cottoncalling://call?person=<id>&video=0|1      Cotton Calling//! cottoncallingdev://call?person=<id>&video=0|1   Cotton Calling Dev//! cottoncalling://call?person=<a>&person=<b>&video=1   a group call//! ```/// Cotton Calling's URL scheme.pub const SCHEME: &str = "cottoncalling";/// Cotton Calling Dev's.pub const DEV_SCHEME: &str = "cottoncallingdev";/// What a call link asks: call these people (one, or a group), by audio or video.#[derive(Debug, Clone, PartialEq, Eq)]pub struct CallLink {    pub people: Vec<String>,    pub video: bool,    /// The link named the development app.    pub dev: bool,}fn unreserved(byte: u8) -> bool {    byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~')}fn encode(text: &str) -> String {    text.bytes().map(|byte| if unreserved(byte) { (byte as char).to_string() } else { format!("%{byte:02X}") }).collect()}fn decode(text: &str) -> Option<String> {    let bytes = text.as_bytes();    let mut out = Vec::with_capacity(bytes.len());    let mut i = 0;    while i < bytes.len() {        match bytes[i] {            b'%' => {                let hex = text.get(i + 1..i + 3)?;                out.push(u8::from_str_radix(hex, 16).ok()?);                i += 3;            }            b'+' => {                out.push(b' ');                i += 1;            }            byte => {                out.push(byte);                i += 1;            }        }    }    String::from_utf8(out).ok()}/// The link that places a call to `people` (one, or a group).pub fn build(people: &[&str], video: bool, dev: bool) -> String {    let named: String = people.iter().map(|person| format!("person={}&", encode(person))).collect();    format!("{}://call?{named}video={}", if dev { DEV_SCHEME } else { SCHEME }, u8::from(video))}/// What a link asks, or none when it is not a call link: another scheme or/// host, no person, more than [`MAX_INVITEES`](super::machine::MAX_INVITEES)/// people, or a `video` that is not 0 or 1. Unknown parameters are ignored;/// a person named twice is one; a repeated `video` is refused.pub fn parse(url: &str) -> Option<CallLink> {    let (scheme, rest) = url.trim().split_once("://")?;    let dev = match scheme.to_ascii_lowercase().as_str() {        SCHEME => false,        DEV_SCHEME => true,        _ => return None,    };    let (host, query) = rest.split_once('?').unwrap_or((rest, ""));    if host.trim_end_matches('/') != "call" {        return None;    }    let mut people: Vec<String> = Vec::new();    let mut video = None;    for pair in query.split('&').filter(|pair| !pair.is_empty()) {        let (key, value) = pair.split_once('=').unwrap_or((pair, ""));        match key {            "person" => {                let person = decode(value)?.trim().to_string();                if person.is_empty() {                    return None;                }                if !people.contains(&person) {                    people.push(person);                }            }            "video" => {                let flag = match value {                    "0" => false,                    "1" => true,                    _ => return None,                };                if video.replace(flag).is_some() {                    return None;                }            }            _ => {}        }    }    if people.is_empty() || people.len() > super::machine::MAX_INVITEES {        return None;    }    Some(CallLink { people, video: video.unwrap_or(false), dev })}#[cfg(test)]#[path = "link_tests.rs"]mod tests;