1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
use crate::error::{ParseSearchTargetError, ParseURNError};
use std::{borrow::Cow, fmt};

#[derive(Debug, Eq, PartialEq, Clone)]
/// Specify what SSDP control points to search for
pub enum SearchTarget {
    /// Search for all devices and services.
    All,
    /// Search for root devices only.
    RootDevice,
    /// unique identifier for a device
    UUID(String),
    /// e.g. schemas-upnp-org:device:ZonePlayer:1
    /// or schemas-sonos-com:service:Queue:1
    URN(URN),
    /// e.g. roku:ecp
    Custom(String, String),
}
impl fmt::Display for SearchTarget {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SearchTarget::All => write!(f, "ssdp:all"),
            SearchTarget::RootDevice => write!(f, "upnp:rootdevice"),
            SearchTarget::UUID(uuid) => write!(f, "uuid:{}", uuid),
            SearchTarget::URN(urn) => write!(f, "{}", urn),
            SearchTarget::Custom(key, value) => write!(f, "{}:{}", key, value),
        }
    }
}

impl std::str::FromStr for SearchTarget {
    type Err = ParseSearchTargetError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s {
            "ssdp:all" => SearchTarget::All,
            "upnp:rootdevice" => SearchTarget::RootDevice,
            s if s.starts_with("uuid") => {
                SearchTarget::UUID(s.trim_start_matches("uuid:").to_string())
            }
            s if s.starts_with("urn") => URN::from_str(s)
                .map(SearchTarget::URN)
                .map_err(ParseSearchTargetError::URN)?,
            s => {
                let split: Vec<&str> = s.split(":").collect();
                if split.len() != 2 {
                    return Err(ParseSearchTargetError::ST);
                }
                SearchTarget::Custom(split[0].into(), split[1].into())
            }
        })
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
#[allow(missing_docs)]
/// Uniform Resource Name
///
/// e.g. `urn:schemas-upnp-org:service:RenderingControl:1`
pub enum URN {
    Device(Cow<'static, str>, Cow<'static, str>, u32),
    Service(Cow<'static, str>, Cow<'static, str>, u32),
}
impl fmt::Display for URN {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            URN::Device(domain, typ, version) => {
                write!(f, "urn:{}:device:{}:{}", domain, typ, version)
            }
            URN::Service(domain, typ, version) => {
                write!(f, "urn:{}:service:{}:{}", domain, typ, version)
            }
        }
    }
}

impl URN {
    /// Creates an instance of a device URN
    pub const fn device(domain: &'static str, typ: &'static str, version: u32) -> Self {
        URN::Device(Cow::Borrowed(domain), Cow::Borrowed(typ), version)
    }
    /// Creates an instance of a service URN
    pub const fn service(domain: &'static str, typ: &'static str, version: u32) -> Self {
        URN::Service(Cow::Borrowed(domain), Cow::Borrowed(typ), version)
    }

    /// Extracts the `schemas-upnp-org` part of the
    /// `urn:schemas-upnp-org:service:RenderingControl:1`
    pub fn domain_name(&self) -> &str {
        match self {
            URN::Device(domain_name, _, _) => domain_name,
            URN::Service(domain_name, _, _) => domain_name,
        }
    }

    /// Extracts the `RenderingControl` part of the
    /// `urn:schemas-upnp-org:service:RenderingControl:1`
    pub fn typ(&self) -> &str {
        match self {
            URN::Device(_, typ, _) => typ,
            URN::Service(_, typ, _) => typ,
        }
    }

    /// Extracts the `1` part of the
    /// `urn:schemas-upnp-org:service:RenderingControl:1`
    pub fn version(&self) -> u32 {
        match self {
            URN::Device(_, _, v) => *v,
            URN::Service(_, _, v) => *v,
        }
    }
}

impl Into<SearchTarget> for URN {
    fn into(self) -> SearchTarget {
        SearchTarget::URN(self)
    }
}

impl std::str::FromStr for URN {
    type Err = ParseURNError;
    fn from_str(str: &str) -> Result<Self, Self::Err> {
        let mut iter = str.split(':');
        if iter.next() != Some("urn") {
            return Err(ParseURNError);
        }

        let domain = iter.next().ok_or(ParseURNError)?.to_string().into();
        let urn_type = &iter.next().ok_or(ParseURNError)?;
        let typ = iter.next().ok_or(ParseURNError)?.to_string().into();
        let version = iter
            .next()
            .ok_or(ParseURNError)?
            .parse::<u32>()
            .map_err(|_| ParseURNError)?;

        if iter.next() != None {
            return Err(ParseURNError);
        }

        if urn_type.eq_ignore_ascii_case("service") {
            Ok(URN::Service(domain, typ, version))
        } else if urn_type.eq_ignore_ascii_case("device") {
            Ok(URN::Device(domain, typ, version))
        } else {
            Err(ParseURNError)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{SearchTarget, URN};

    #[test]
    fn parse_search_target() {
        assert_eq!("ssdp:all".parse(), Ok(SearchTarget::All));
        assert_eq!("upnp:rootdevice".parse(), Ok(SearchTarget::RootDevice));

        assert_eq!(
            "uuid:some-uuid".parse(),
            Ok(SearchTarget::UUID("some-uuid".to_string()))
        );

        assert_eq!(
            "urn:schemas-upnp-org:device:ZonePlayer:1".parse(),
            Ok(SearchTarget::URN(URN::Device(
                "schemas-upnp-org".into(),
                "ZonePlayer".into(),
                1
            )))
        );
        assert_eq!(
            "urn:schemas-sonos-com:service:Queue:2".parse(),
            Ok(SearchTarget::URN(URN::Service(
                "schemas-sonos-com".into(),
                "Queue".into(),
                2
            )))
        );
        assert_eq!(
            "roku:ecp".parse(),
            Ok(SearchTarget::Custom("roku".into(), "ecp".into()))
        );
    }
}